box2dweb

How can I get the canvas context to follow a body in Box2dWeb?


I am uing Box2D.Dynamics.b2DebugDraw to render my Box2dWeb world. How can I get the canvas to remain centered on a moving body?

var debugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvasElement").getContext("2d"));
debugDraw.SetDrawScale(30.0);
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit | Box2D.Dynamics.b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);

And here in the loop that runs the simluation:

window.setInterval( function(){
    _this.world.Step(
        1 / 60   //frame-rate
        ,  10       //velocity iterations
        ,  10       //position iterations
    );
    _this.world.DrawDebugData();
    _this.world.ClearForces();
}, 1000 / 60);

Solution

  • Translate the canvas element in the run loop:

    var renderingContext = document.getElementById("canvasElement").getContext("2d");
    debugDraw.SetSprite(renderingContext);
    
    // .... snip .....
    
    window.setInterval( function(){
        // ...
        renderingContext.translate(someX, someY); // <--- interesting line
        _this.world.DrawDebugData();
        _this.world.ClearForces();
    }, 1000 / 60);