# Face an point

## Recommended Posts

Hello, I have been trying to get the best way to make a function that rotates my character to face a specific point. I have done something like this:

#define PIOVER180  0.0174532925199432957692369076848861f

float rot;

void Face(float pointX, float pointZ)
{
float x = pointX - PlayerX;
float z = pointZ - PlayerZ;
if (x!=0 && z<0)
{
rot=((atanf(x/z))/PIOVER180)-180;
}
if (x!=0 && z>0)
{
rot=((atanf(x/z))/PIOVER180);
}
}


glRotatef( rot-90.0f, 0.0f, 1.0f, 0.0f ); -- Draw my character -- If someone have any better way to do this please feel free to post. Thanks.

##### Share on other sites
jyk    2094
I would suggest looking into the atan2() function as an alternative to atan(); it's more stable, and will simplify the code (you won't have to determine the quadrant manually).

##### Share on other sites
Palidine    1315
To make it look better in game (your current algorithm appears to "snap" the player to the facing angle) you want to clamp the rotation to no more than some max value. i.e. no more than 5degrees per second or whatever number looks good.

You find the angle between the current facing direction and the desired facing direction. if that is 30degrees clockwise, then you'd only rotate Xdegrees clockwise this frame where X is calculated based on your clamping angle.

For extra credit make that max rotation rate tunable in data somewhere so you don't have to re-compile to tune the visual result. for super-extra credit, make it so that you don't have to restart the game to change the number. =)

-me

##### Share on other sites
jyk:

Yah I will look into that, thanks.

Palidine:

About that you said, if you have time to make some example on how to do it? Thanks.

##### Share on other sites
Palidine    1315
Quote:
 Original post by X5-ProgrammerAbout that you said, if you have time to make some example on how to do it? Thanks.

Sadly, no. What I wrote should be enough of an algorithm for you to code it. Was there a specific bit of what I described that was confusing?

-me

##### Share on other sites
Ozymandias42    181
Quote:
 Original post by jykI would suggest looking into the atan2() function as an alternative to atan(); it's more stable, and will simplify the code (you won't have to determine the quadrant manually).

Thank you for bringing this function to my attention. I've always used atan() myself. Yay new and better information!

##### Share on other sites
Palidine:

Yah I can try to make it, Thanks!

##### Share on other sites
dijster    123
Try this
angle = ATan2(y1-y2,x1-x2)-90