Search code examples
javascriptbox2dphysicsphysics-engineemscripten

Box2d.js impulses/forces and initial position


I was "playing" with kripken's box2d when I had a pair of issues. I chose this fork because it seems to be the fastest and the most used.

  1. API defines position on bodyDef but you 'must' give it on body.
  2. Forces, impulses, ... keep attached to the body giving a unexpected constant velocity.

Does anybody get these behaviours before? Does anybody have any hints?

This comes from a complex app but I have simplified for demo:

<html>
<head>
    <script src="http://kripken.github.io/box2d.js/box2d.js"></script>
</head>
<body>
<script>
    // gravity 0 for top view scene
    var world = new Box2D.b2World( new Box2D.b2Vec2(0, 0), true);

    var bodyDef = new Box2D.b2BodyDef();
    bodyDef.set_type( Box2D.b2_dynamicBody );
    bodyDef.set_position(40,40);

    var body = world.CreateBody(bodyDef);
    // ISSUE 1
    // without these two lines real position is 0,0
    body.GetPosition().set_x(40);
    body.GetPosition().set_y(40);

    var dynamicBox = new Box2D.b2PolygonShape();
    dynamicBox.SetAsBox(5.0, 5.0);

    var fixtureDef = new Box2D.b2FixtureDef();
    fixtureDef.set_shape(dynamicBox);
    fixtureDef.set_density(1);
    fixtureDef.set_friction( 0.8);
    fixtureDef.set_restitution( 0.5);

    body.CreateFixture(fixtureDef);

    //ISSUE 2 
    // Never ending movements
    //body.ApplyLinearImpulse(new Box2D.b2Vec2(5,5),body.GetWorldCenter());
    body.ApplyForce(new Box2D.b2Vec2(50,50),body.GetWorldCenter());

    function update() {
        world.Step(1/30, 10, 10);
        world.ClearForces();    
        console.log(body.GetPosition().get_x()+","+body.GetPosition().get_x());
    }

    setInterval(update, 1000/60);

</script>
</body>
</html>

Solution

  • For issue 1, set_position should expect a b2Vec2 parameter. Try this:

    bodyDef.set_position( new b2Vec2( 40, 40 ) );