Luke Alderton
Luke Alderton

Reputation: 3296

rotate player to face planet

So I'm having trouble making my placer face a planet. I have the angle between the player and the planet, I also have the angle that the player is currently at, now what I want to do with these is make my player face the planet but with an incremental change. (I do this because I want my placer to be able to orbit the planet)

The problem is with the math, I increment the player rotation to match the angle between the player and the planet however because angles work in 0 to 360 my player won't orbit because player rotation might be 2 however angle to planet is 280 so the game will turn the player around, sorry for the bad explanation.

Does anyone know how to make my player successfully orbit my planet?

Here is my code:

double rotation = Math.toDegrees(Math.atan2(currentPlanet.pos[1]-currentPlayer.pos[1], currentPlanet.pos[0]-currentPlayer.pos[0]));
if(rotation < 0)
{
    rotation += 360;
}

if(currentPlayer.rotation < rotation)
{
    currentPlayer.rotation += 0.15*delta;
}

if(currentPlayer.rotation > rotation)
{
    currentPlayer.rotation -= 0.15*delta;
}

Upvotes: 2

Views: 229

Answers (2)

Piotr Praszmo
Piotr Praszmo

Reputation: 18330

The problem is 350° is also -10°. You want the smaller absolute value.

The solution is very simple. Use modulo operation to translate your angles into correct range.

/* returns angle x represented in range -180.0 ... 180.0 */
double clampAngle(double x) {
    return (x%360.0+360.0+180.0)%360.0-180.0;
}

Pass your angle difference to this function. Sign of the result will tell you in which direction you should turn:

double rotation = Math.toDegrees(Math.atan2(currentPlanet.pos[1]-currentPlayer.pos[1], currentPlanet.pos[0]-currentPlayer.pos[0]));
double diff =  ((rotation-currentPlayer.rotation)%360.0+360.0+180.0)%360.0-180.0;   

if(diff>0)
    turn right
else
    turn left

You might want to not turn at all if abs(diff) is very small.

I'm not sure if it will make your player orbit your planet. You will need to set correct angular and linear speed.

Upvotes: 3

Steven
Steven

Reputation: 191

What you want is to make your player rotate to face either plus or minus 90 degrees of the angle you've computed between the planet and the player. Orbit occurs when all movement is tangent (90 degrees) to the planet.

So, compute the angle, compare the player angle to both the +90 and the -90, and rotate your player toward the closer of the two.

Upvotes: 1

Related Questions