gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Coding > Calculating the angle between 2 points

#4745 - Alunze - Tue Apr 08, 2003 12:46 pm

I've got this problem: I have 2 points on screen; then, if I were to draw a line from the first point to the second, how could I obtain the angle (inclination) of that line, preferably in a quick way?

I thought of calculating it using arctan (the line would be the hypotenuse, the x and y differences would be the other 2 sides of the triangle), but tan values vary way too much to be included in a table, and for some values, tan is +/- infinite. Os maybe I am wrong, I was never that good on trygonometry...

Thanks in *Advance* >_6

#4753 - Xok - Tue Apr 08, 2003 4:07 pm

Note: Let v and u be vectors.

cos ang((u,v)) = ( u.v ) / ( |u| . |v|)

ang(u,v) is the angle betwen u and v.
|u| in the module of u.


Example:
Y
|....................x p2(4,4)
|
|..........x p1(2,2)
|
O------------------------------------------Z

Let be u the vector (1,0) directional vector of the OX axis
Let be v the vector (2,2) = (4,4) - (2,2)

then cos(ang(u,v)) = (1,0) . (2,2) / [ | (1,0) | * | 2, 2 | ]


(a,b) . (c, d) = ac+ bd

| (a , b) | = sqrt( a^2 + b^2 )


then cos(ang(u, v)) = 2/ [sqrt( 1^2+0^2) * sqrt (2^2+ 2^2)] = 2 / [ 1 * 2 * sqrt (2)] =
1/sqrt(2)

then ang(u,v) = arcos (1/sqrt (2)) = 45 ? (o PI / 4 en radianes).

#4756 - tom - Tue Apr 08, 2003 4:42 pm

Alunze wrote:
I've got this problem: I have 2 points on screen; then, if I were to draw a line from the first point to the second, how could I obtain the angle (inclination) of that line, preferably in a quick way?


so you need a line drawing algorithm: http://www.gamedev.net/reference/articles/article767.asp

#4760 - tepples - Tue Apr 08, 2003 5:28 pm

Alunze wrote:
but tan values vary way too much to be included in a table, and for some values, tan is +/- infinite.

If you write your arctan2() right, it will not vary infinitely. The key is to decide whether to use y/x or x/y for each call based on which has a smaller absolute value. See previous arctan discussion for details.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.