7
\$\begingroup\$

I found out about this using a debug renderer. When the game starts, everything is in order. But when a collision happens, the sprite's rotation is way larger than its body. The sprite and body match when the body is completely horizontal.

sprites with Box2D body outlines as overlay

The sprite's rotation origin seems far distant from where it should be. Here's my code:

Sprite sprite = data.sprite;
position = body.getPosition();
sprite.setPosition(
    position.x - sprite.getWidth()  / 2,
    position.y - sprite.getHeight() / 2
);
sprite.setOrigin(position.x, position.y);
sprite.setRotation(MathUtils.radiansToDegrees * body.getAngle());

As you can see, I am even trying to set center of its rotation with setOrigin without success. How can I fix this?

\$\endgroup\$

1 Answer 1

9
\$\begingroup\$

Most APIs represent the Sprite's origin in local space, not in world space. This is supported by libgdx's documentation which states:

A Sprite also has an origin around which rotations and scaling are performed (that is, the origin is not modified by rotation and scaling). The origin is given relative to the bottom left corner of the Sprite, its position.

So I think that if you want rotations to happen around the center of the sprite, you should be using the following origin instead:

sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
\$\endgroup\$
2
  • \$\begingroup\$ You are really fast. You are right about setOrigin. That was the trick. Thanks a lot! BTW, setPosition statement should be from mine. You need to set corner point for sprite position. \$\endgroup\$ Jan 18, 2012 at 5:42
  • \$\begingroup\$ @Paul I noticed the problem and edited my post but you had already commented. :) In some APIs the origin also affects translation (which is why I initially wrote a different setPosition) but then I checked the documentation and found out that's not the case with libgdx so your setPosition was correct. \$\endgroup\$ Jan 18, 2012 at 5:47

You must log in to answer this question.

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