I am creating a Box2d World in Java script and I am not adding any objects in it. I am setting the gravity to zero. When I try to draw the box2d Objects inside a canvas, if any exist, I find a rectangle drawn at 0,0. However, when I use DebugDraw() no objects are displayed as expected. Can someone explain why is the additional rectangle getting drawn? The code is below:
canvas=document.getElementById("cnv");
context=canvas.getContext("2d");
x=0;
y=0;
scale=100;
gravity=new b2Vec2(0,0);
world=new b2World(gravity,false);
requestAnimFrame(main);
function main()
{
requestAnimFrame(main);
begin();
}
function begin()
{
world.Step(1/60,10,10);
drawObjects();
world.ClearForces();
}
function drawObjects()
{
canvas.width=canvas.width;
for (currentBody = world.GetBodyList(); currentBody; currentBody =currentBody.m_next)
{
position = currentBody.GetPosition();
if (currentBody.GetType() == b2Body.b2_staticBody)
{
context.fillStyle="red";
alert(position.x+" "+position.y);
context.fillRect(position.x*scale,position.y*scale,125,125);
}
}
}
I found that the reason a rectangle is drawn even though I have not added any object is that I am hard coding the height and width as 125. If I changed the code such that the height and width are taken dynamically from the box2d world, the rectangle is not created as no objects exist in the world.