Face an point

Started by
6 comments, last by dijster 17 years, 4 months ago
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.
-[ thx ]-
Advertisement
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).
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
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.
-[ thx ]-
Quote:Original post by X5-Programmer
About 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
Quote:Original post by jyk
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).


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

Yah I can try to make it, Thanks!
-[ thx ]-
Try this
angle = ATan2(y1-y2,x1-x2)-90
http://www.ininja.co.uk

This topic is closed to new replies.

Advertisement