How to center a sprite on a Box2D body?

I googled and could not find a good explanation.

Currently, when I am creating the entity, this is done:


getSprite().setOrigin(getSprite().getWidth() / 2, getSprite().getHeight() / 2);
getSprite().setPosition(getBody().getPosition().x, getBody().getPosition().y);

This is where the sprite is rendered, which is undesirable. I know it is because the Body is rendered at a point using its center and the sprite is rendered at a point using its bottom-left corner. I attempted changing the origin of the Sprite, but this changed nothing when being rendered, as seen above. The position of the Sprite was the same with or without changing the origin. I think the origin only has to do with scaling and rotating, but I may be wrong.

Can anyone tell me how to make the sprite always center on the Box2D body? Thank you.


getSprite().setOrigin(getSprite().getWidth() / 2, getSprite().getHeight() / 2);
getSprite().setPosition(getBody().getPosition().x - getSprite.getOriginX(), getBody().getPosition().y - getSprite().getOriginY());

Think about it. You have a sprite that is 32x32. It’s origin starts at 0,0 by default. But Box2D bodies are created with a centre origin point.

So if you set the origin to half the width and height of the sprite, the origin would be 16,16.

If we have a body that is 32x32 at it is positioned at 16,16 (which is with the bottom left corner of the body right in the bottom left of the screen) and then we position a sprite at that position the sprites centre point would be at 48,48 and the bottom left corner of the sprite would be at 32,32. So subtract the origin from that and bang, it’s all good.

Another option would be:


getSprite().setOrigin(getSprite().getWidth() / 2, getSprite().getHeight() / 2);
getSprite().setPosition(getBody().getPosition().x - (getSprite().getWidth() / 2), getBody().getPosition().y - (getSprite().getHeight() / 2));

It depends what you are doing, for me I tend to use the origin method for drawing and the other method for grid based positions (snapping grid).

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/g2d/Sprite.html#setCenter-float-float-

Vector2 pos = body.getPosition();
sprite.setCenter(pos.x, pos.y);

Well that is new :|.

Or use DermetFan Box2DUtils

Doing this causes the Sprite not to show up at all.


	public void changeSpriteTo(Sprite sprite)
	{
		setSprite(sprite);
		setTexture(sprite.getTexture());
		getSprite().setCenter(getBody().getPosition().x, getBody().getPosition().y);
		System.out.println(getBody().getPosition());
	}

The print statement prints [5.0:5.0]

It’s off-screen then.

Ah. It had to do with me setting the size after changing its center. Sorry for the confusion, and thank you both for the help.

I did not know that functionality existed in LibGDX.