2
\$\begingroup\$

I'm creating game like hill climb racing.

I created my car with the help of shapes and joints but I don't know how to attach graphics to it. I used actors and sprites before for the sake of learning, but I don't know how to use those with box2d bodies.

How can I?

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ well, actually, the best way would be to use both methods - use composition class (like in solution 2), and then set the userData to the composite object... that way you get a) easy access to data from physics routines, b) have the cleanest abstraction via proper composition pattern, c) can easily introduce custom logic to the object. That's exactly why most (if not all) game frameworks have some kind of entity class, that serves as a "junction point" for all of the game entity functionalities (visual, physical, AI-related etc). \$\endgroup\$ – user40973 Jun 27 '15 at 21:40
1
\$\begingroup\$

You can use the setUserData method to attach an Object to the box2D body (like for example a Sprite or an Actor):

body.setUserData(sprite);

Accordingly you can get your Sprite back like this:

(Sprite) body.getUserData();

Note that you need to cast to Sprite.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.