Search code examples
box2dgame-physicsbox2d-iphonephysics-engine

How to smoothly rotate a character according to the slope it is walking onto/standing on?


I need to rotate a character sprite according to the scope of the platform he (a rectangle) is standing or walking on. I have achieved the effect by rotating it according to the slope of the platform he is standing on. But there are two problems:

First, the rotation is not smooth. When the character walks from a flat platform onto a sloped one, it is rotated instantly and also because of that rotation it is pushed up by a little bit.

Second, once he walks off the slope and onto a flat platform again, I cannot rotate the character accordingly. This is because at that point the character would be colliding with both a flat platform and a sloped one (they are placed together), so for a few steps the character will be rotating crazily back and forth because two collision detection functions working together.

I have tried to solve it by detecting the facing of the character and try to figure out which point (left or right) of him touches something first, but it was not working, because I can only detect collision, but not "no collision" or "when character leaves some platform".

I have attached an illustration of the situation. Please help, thanks!

PS: Since I am not allowed to post images, please visit: https://i.sstatic.net/jqPjt.png for the image. Thanks.


Solution

  • Your rotation seems off. You need to be rotating around the base of the character rectangle. That would solve some of your problems, but not all.

    The case where the character is in contact with 2 platforms needs to be handled. Currently I guess you're just extracting an angle directly from the platform and assigning that to the character. That's not going to cut it because you need arbitrary angles when you have different contact points.

    Solution is to create a vector between the 2 contact points, then take the components of the vector x,y and call atan2(x, y). This will give the angle between the contacts in radians. Be sure you get the parameters the right way around! Game development requires you know trigonometry and vector math. What's happening here is we're creating an axis-aligned right-angled triangle with the hypotenuse being defined by the two contact points, then we flip the triangle around and get the angle using tan = opp/adj by swapping the x and y components.

    Note that you need to be sure that the contact points are always given in a specific order, or you will end up rotating at a weird angle, because the triangle you create will be facing the other direction. You may need to do something like sort based on x coordinate first.