getting the exact location of a Box2D body in libgdx

Started by
1 comment, last by Alberth 5 years, 6 months ago

Forgive me for the somewhat inappropriate title for my question.

I can't seem to keep my game objects in sync with a box2d body.

I understand these much:

1. When you get a body position, you need to subtract half the size of your sprite to get the exact location

2. box2d uses radians for angles, so you need to convert to degrees.

Everything was going well when I used CircleShape and PolygonShape's setAsBox() method to create my shapes, but when I created a triangle using my own vertices, the shape was drawn correctly but now my sprite is no longer following the body correctly.

 

Please what am I doing wrong or what am I not doing?

 

Advertisement

Never used Box2D, but when switching between coordinate systems, you always position the origin of the inner coordinate system relative to the origin of the surrounding coordinate system. In other words, your sprite origin has an offset-vector from the body origin. You typically specify that when you add the element (in your case the sprite). If you didn't specify anything, it is probably (0, 0, 0), as that is a common default for relative position.

Consult the documentation or the code (documentation) to check what it does exactly during "add".

 

As for radians versus degrees, degrees are nicer for communicating angles. "30" is nicer to write for a person than "pi/6" or its approximation "0.5235987755982988". For computing with angles in trigeometry etc, radians make a lot more sense. This is why most math libraries use radians. The simpler alternative is therefore to drop degrees altogether in your code, and use radians everywhere. It takes a little getting used to it, but in a month or so, you'll find pi/2 just as intuitive as 90.

This topic is closed to new replies.

Advertisement