I have seen two ways of achieving this, one is to let the UserData of the Box2D Body
hold the Sprite
.
body.setUserData(mySprite);
And in the update you retrieve that and apply position and rotation to the Sprite
according to the Body
's transform;
Sprite sprite = (Sprite)body.getUserData();
Vector2 position = body.getPosition();
// Center body is center sprite here
float hw = sprite.getWidth() / 2.0f;
float hh = sprite.getHeight() / 2.0f;
float a = body.getAngle() * MathUtils.radiansToDegrees;
float x = position.x - hw;
float y = position.y - hh;
sprite.setPosition(x, y);
sprite.setRotation(a);
The other approach is to keep track of an object that is the amalgamation of the Sprite
and the Body
;
public class MyGameObject {
private Body body;
private Sprite sprite;
public void update() {
Vector2 position = body.getPosition();
// Center body is center sprite here
float hw = sprite.getWidth() / 2.0f;
float hh = sprite.getHeight() / 2.0f;
float a = body.getAngle() * MathUtils.radiansToDegrees;
float x = position.x - hw;
float y = position.y - hh;
sprite.setPosition(x, y);
sprite.setRotation(a);
}
}
I think it's largely a matter of preference, I prefer the UserData approach myself as I need to "manually" keep track of less things that way.