Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to make a rope-like constraint where the constraint is like a spring that bounces back.

I'm trying to use the constraint component:

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

But it seems to work with fixed distances. How can i make a spring ?

like image 204
Piotr Adam Milewski Avatar asked Nov 29 '25 19:11

Piotr Adam Milewski


1 Answers

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

Check it out in this fiddle.

like image 128
Piotr Adam Milewski Avatar answered Dec 03 '25 09:12

Piotr Adam Milewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!