Nikolay Yenbakhtov
Nikolay Yenbakhtov

Reputation: 443

Link between your sprites or game objects and Box2D

I have a problem: in libgdx documentation about box2d (libgdx box2d) in the section Sprites and Bodies, there is explanation how to set link between your sprites or game objects and Box2D, but when I'm trying to get setPosition method, I can't get it (my Entity object e has no such method like setPosition).

I don't understand which type of Entity I should use here (is it libgdx entity or Java entity class)?

code:

In show() method

private Texture ballTexture = new Texture("images/ball.png");  
private Image ballImage = new Image(ballTexture);
body.setUserData(ballImage);
stage.add(ballImage);

In render() method

// Create an array to be filled with the bodies
// (better don't create a new one every time though)
Array<Body> bodies = new Array<Body>();
// Now fill the array with all bodies
world.getBodies(bodies);

for (Body b : bodies) {
    // Get the body's user data - in this example, our user 
    // data is an instance of the Entity class
    Entity e = (Entity) b.getUserData();

    if (e != null) {
        // Update the entities/sprites position and angle
        e.setPosition(b.getPosition().x, b.getPosition().y);
        // We need to convert our angle from radians to degrees
        e.setRotation(MathUtils.radiansToDegrees * b.getAngle());
    }
}
stage.act();
stage.render();

I stopped at the line e.setPosition(b.getPosition().x, b.getPosition().y); because I can't get setPosition() method in e object. What may be wrong?

Upvotes: 1

Views: 118

Answers (1)

Chanandler Bong
Chanandler Bong

Reputation: 518

In the below piece of code:

private Image ballImage = new Image(ballTexture);
body.setUserData(ballImage);

you set an object of type Image as user data.

This means that you should cast b.getUserData(); into Image, not Entity:

Image e = (Image) b.getUserData();

Image has setPosition and setRotation methods inherited from Actor.

Upvotes: 1

Related Questions