Search code examples
c++box2dgame-physics

Keep object the right way up on the surface of a planet


I'm using Box2D to simulate a person walking on a planet. I calculate a custom gravity toward the center of the planet and it's working correctly except for one glitch: The box I'm using as the physical model for the person currently rotates as it moves around the planet. I want it to be always the right way up. How do you suggest I do this?

I've thought about taking the gravity vector and calculate the tangential vector when the person's feet is touching the ground, but I'm not quite sure about how to do that. If this is the best way, can you please explain how to achieve that? Aren't there any easier ways?


Solution

  • There is an easier way.

    I am assuming that by "right way up" you mean that the feet should always point to the planet.

    Do the following:

    • Place an additional circular body at the same position as your planet (basically a small circle that is "inside" your planet). That body should neither have collision with your planet nor with your player.
    • Connect this body to your planet by a revolute joint so that it stays fixed to the same position but may rotate.
    • Connect your player to this body by a prismatic joint set the axis according to where the player starts in relation to the planet (e.g. if the player starts on top of the planet, set the axis to (0,1)).

    If you do that, the prismatic joint should take care of keeping your player rotation the way you want it.

    If you prefer to set the angle manually I think that you can calculate the angle by using atan2 like this:

    Math.atan2(planetPos.y - playerPos.y, planetPos.x - playerPos.x);

    This will calculate an angle in degrees though. You'll have to convert it to radians to use it in Box2D.