cannon.js icon indicating copy to clipboard operation
cannon.js copied to clipboard

spring example?

Open trusktr opened this issue 6 years ago • 3 comments

Which example, if any, shows how to use the Spring?

trusktr avatar Feb 28 '19 09:02 trusktr

This should be useful... http://schteppe.github.io/cannon.js/demos/spring.html

It's at the very left bottom on the examples page.

swift502 avatar Feb 28 '19 18:02 swift502

Hi there! Following up on this question. I want to add springs inside a for loop. So far I tried this inside the loop:

        	var spring = new CANNON.Spring(spheresarray[k],spheresarray[j],{
                  localAnchorA: new CANNON.Vec3(0,0,0),
                  localAnchorB: new CANNON.Vec3(0,0,0),
                  restLength : Math.sqrt(distsqr),
                  stiffness : 500,
                  damping : 1,
            });
    		world.addEventListener("postStep",function(event){
        		spring.applyForce();
		});

But this seems to be only adding to the world one spring, I think the last one. I guess my loop is just overwriting the spring variable multiple times that's why at the end of the loop I've only added one. But how do I add all of them? Maybe something like creating an array of springs? But I have no idea how..

Thanks for any help!

labriata avatar Oct 04 '19 15:10 labriata

If you haven't already you'd need push references to the springs into an array to traverse through in your "postStep" handler.

let spring = new CANNON.Spring(spheresarray[k],spheresarray[j],{
     localAnchorA: new CANNON.Vec3(0,0,0),
     localAnchorB: new CANNON.Vec3(0,0,0),
     restLength : Math.sqrt(distsqr),
     stiffness : 500,
     damping : 1,
});

springsArray.push( spring );

// outside of loop
world.addEventListener("postStep",function(event){
     springsArray.forEach( ( spring, i ) => {
          spring.applyForce();
     }
});

ghost avatar Jan 27 '21 10:01 ghost