Sprites misaligned with bodies, can't find bug in the display loop

50 views Asked by At

I'm currently creating a game with box2Dweb. Whenever my shapes move toward the bottom-right corner of the canvas, their sprite seems to move with some offset that grows bigger and bigger (and if I move the shape toward the top left corner of the canvas, the sprite aligns better and better), and I really can't see why. Do you guys see something wrong on my display loop ?

I'm creating square cubes with this snippet:

this.createSquare= function(x, y, bodyDef, fixtureDef, object){
    if(object.isStatic){
        bodyDef.type = b2Body.b2_staticBody;
    }else{
        bodyDef.type = b2Body.b2_dynamicBody;
    }
    fixtureDef.shape = new object.shape;
    polygonShape = fixtureDef.shape;
    polygonShape.SetAsBox(object.width,object.height);
    bodyDef.position.Set(x/game.worldScale,y/game.worldScale);
}

And I use this function in my display loop to display some sprites on it:

for(var i=0; i < tab.length; i++) {
        context.save();
        console.log(context);
        context.translate(tab[i].GetBody().GetPosition().x * 30, tab[i].GetBody().GetPosition().y * 30);
        context.rotate(tab[i].GetBody().GetAngle());
            var dataResize = { 'image'    : tab[i].GetUserData().img,
                               'imgPosX'  : tab[i].GetBody().GetPosition().x,
                               'imgPosY'  : tab[i].GetBody().GetPosition().y,
                               'imgWidth' : tab[i].m_shape.m_vertices[2].x*60,
                               'imgHeight': tab[i].m_shape.m_vertices[2].y*60
            }
            context.drawImage(
                        dataResize.image, 
                        (dataResize.imgPosX) - (dataResize.imgWidth/2), //img pos x
                        (dataResize.imgPosY) - (dataResize.imgHeight/2), //img pos y
                        dataResize.imgWidth, //img wdith
                        dataResize.imgHeight //img height
                    )
        context.restore();
    }

What am I missing ? I've tried reading pretty much everything I could find on SOFLOW and couldn't see the issue.

Thanks

1

There are 1 answers

0
Valentin Roudge On BEST ANSWER

Okay, found what was wrong:

In the drawImage I did

(dataResize.imgPosX) - (dataResize.imgWidth/2), //img pos x
(dataResize.imgPosY) - (dataResize.imgHeight/2), //img pos y

When I was supposed to do

(-dataResize.imgWidth/2)

instead !