objects direction calculation

Started by
9 comments, last by Craazer 21 years, 6 months ago
Doesn any one know how to do this? if i have object whit 360 degrees its postion is x y and i want it to face x2 y2 so how do i calculate it?
Advertisement
Short answer:
angle = atan((y2 - y) / (x2 - x)); 
Post if you want the long answer (ie if you don't understand the trigonometry behind it)

John B

[edited by - JohnBSmall on October 19, 2002 5:55:10 PM]
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
quote:Original post by JohnBSmall
Short answer:
angle = atan((y2 - y) / (x2 - x));  
Post if you want the long answer (ie if you don''t understand the trigonometry behind it)

John B

[edited by - JohnBSmall on October 19, 2002 5:55:10 PM]


nope im afraid i dont know about it. that atan returns shometing like 1.383852

so what do i do whit that value?

the atan returns a radiant
convert it to normal degrees

180°==PI

degree*PI/180->radiant
radiant*180/PI->degree
http://www.8ung.at/basiror/theironcross.html
Yeah, sorry. Basiror is right, atan returns the angle in radians. My bad .

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.

This code doesnt work:


  double radiant = atan(( (des_y - y) / (des_x - x) ));int direction = (radiant * 180 / PI); // 0 - 360  


that gives me really wierd direction, what did i do wrong?
It gives you the angular difference between the two orientations. If you just want a new angle, use atan(des_y/des_x).

And; the answer will be between 0 and 180 (or 90 and 270?), not 0 and 360. Add 180 if des_y is negative (unless I''m wrong, of course.)
The range of tan-1 will be the same as the [periodic] domain of tan. Thus, tan-1 will return a value between -PI/2 and PI/2. However, since the quotient of two negative numbers has the same sign as the quotient of two positive numbers (and +/- has the same sign as -/+), you still have to determine whether the result could simply be a reference angle, and that the object could really be in quadrant 2 or 3.

[edited by - Zipster on October 22, 2002 7:00:29 PM]

        float ToAngle(float x, float y){	if (x == 0)	{		if (y == 0) return .0f;		else if (y > 0) return PI/2;		else return PI*3/2;	}	else if (x > 0)	{		return atanf(y/x);	}	else		return PI+atanf(y/x);}    


I'm surprised that noone caught the divide-by-zero possibilities.

Pass this function (x2 - x, y2 - y) for your purposes.

This returns angle in radians, 0 if the angle is undefined (x=0 and y=0)

To go to degrees, multiply the return value by 57.2958 (that's short for 180/PI)

[edited by - Nypyren on October 22, 2002 11:23:40 PM]
Why don''t you simply use atan2(x,y) ??

This topic is closed to new replies.

Advertisement