如何在框架中创建 spring 和 cannon.js

How to create a spring in a-frame and cannon.js

我正在尝试制作一个类似绳索的约束,其中的约束就像一个 spring 会反弹回来。

我正在尝试使用约束组件:

<a-box id="other-box" dynamic-body />
<a-box constraint="target: #other-box;" dynamic-body />  

但它似乎适用于固定距离。我怎样才能制作 spring ?

CANNON.js

Cannon.js has its very own Spring。它具有三个基本选项的构造函数如下所示:

new CANNON.Spring(bodyA, bodyB, {  // bodies attached to the spring
    restLength: 2,                 // spring length when no force applied
    stiffness: 50,                 // how much can it stretch
    damping: 1,                    // how much will it suppress the force
});

还需要在物理计算的每一步上对附着体施加 spring 力:

world.addEventListener("postStep", function(event) {
  spring.applyForce();
});

还有更多选项,请务必在 docs 中查看它们并尝试一下!


AFRAME

如何搭配a-frame使用?当使用 a-frame physics system.

时,您可以使用 cannon.js

您可以创建一个 aframe 组件,这将创建 spring。确保 physics 正文已加载:

AFRAME.registerComponent("spring", {
   schema: {
      target: {
        type: 'selector'
      }
   },
   init: function() {
     let data = this.data
     let el = this.el
     if (this.el.body) {  
       // check whether we can access the physics body
       this.createSpring()
     } else {             
       // or wait until it's loaded
       this.el.addEventListener("body-loaded", () => {
       this.createSpring()
     })
    }
   },
   createSpring: function() {
    let data = this.data
    let cannonWorld = this.el.sceneEl.systems.physics.driver.world
    var spring = new CANNON.Spring(this.el.body, data.target.body, {
      restLength: data.restLength,
      stiffness: 100,
      damping: 1,
    });
    // Compute the force after each step
    canonWorld.addEventListener("postStep", function(event) {
      spring.applyForce();
    });
   }
})

HTML

<a-box position="0 2.6 -2" id="other-box" color="blue" static-body></a-box>
<a-box position="0 2 -2" color="green" dynamic-body spring="target: #other-box"></a-box>

在这个 fiddle 中查看。