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

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

CANNON.js

Cannon.js has its very own Spring. Its constructor with three basic options looks like this:

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
});

It is also necessary to apply the spring force to the attached bodies on each step the physics are calculated:

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

There are a few more options, be sure to check them out in the docs and experiment a bit!


AFRAME

How to use it with a-frame ? You can work with cannon.js, when using the a-frame physics system.

You can create an aframe component, which will create the spring. Make sure the physics body is loaded though:

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 its 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>

Check it out in this fiddle.

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

Leave a Reply

Your email address will not be published. Required fields are marked *