0
\$\begingroup\$

I am trying to create a bounding box for my sprite using box2d, but the box is being created at the wrong spot. I followed a tutorial on the wiki using this code

    BodyDef bodyDef1 = new BodyDef();
    bodyDef1.type = BodyDef.BodyType.DynamicBody;
    bodyDef1.position.set(player.getX(), player.getY());
    playerBody = world.createBody(bodyDef1);
    PolygonShape square = new PolygonShape();
    square.setAsBox(player.getWidth() / 2, player.getHeight() / 2);
    FixtureDef fixtureDef1 = new FixtureDef();
    fixtureDef1.shape = square;
    fixtureDef1.density = 0.1f;

Player is a just the sprite that I am trying to create the box around.

enter image description here

\$\endgroup\$
1
  • \$\begingroup\$ Hi there! Welcome to GDSE. Have you seen this answer? Does it answer your question as well? \$\endgroup\$ Apr 21, 2015 at 22:16

1 Answer 1

2
\$\begingroup\$

The position of a Box2D body is defined as its center. So if you set the body's position to the lower left corner of the Sprite, then it will be displayed as you showed in the image.

What you need to do is set the Body's position to the center of the Sprite like so:

bodyDef1.position.set(player.getX() + player.getWidth() / 2, player.getY() + player.getHeight() / 2);
\$\endgroup\$
3
  • \$\begingroup\$ I've tried that but it doesn't work. My problem must be elsewhere. \$\endgroup\$
    – user64317
    Apr 22, 2015 at 23:04
  • \$\begingroup\$ @user64317 Do you have the sprite moving around the screen? When adjusting the body you might have forgotten to apply my fix there. Or possibly you are setting the sprite's position based on the body's position, which you lead you to the same problem. You would then have to subtract half of the sprite's height in width. \$\endgroup\$ Apr 22, 2015 at 23:40
  • \$\begingroup\$ Ah I have the sprites position being set based on the bodies position in my update method. Thanks! \$\endgroup\$
    – user64317
    Apr 22, 2015 at 23:51

Not the answer you're looking for? Browse other questions tagged .