This topic is now archived and is closed to further replies.


Implementing cosine algorithm to angle checking

Recommended Posts

Afterlife    122
c>2 = a>2 * b>2 * 2 * cos(angle), Can someone tell how it's done properly? I have two points and I need to check the angle between them compared to 0 degrees. I imagined a triangle that has player's coords as one point, mouse coords as another one and a imaginary point 1 unit up from player coords. Example :
     //Let's pretend this is as a triangle

i_ //imaginary

p\..\_ //player

...\__.......m //mouse

Here is my attempt to implement the algorithm :
//a is the side that goes from player crds to imaginary point

//b is the other side of the triangle, it goes from player crds to mouse crds

//c is the side opposite to the angle, it goes from i to m

if(mouse_x<xplayer) angle+=pii;
The result is no where near what I expected. Anyone know how to implement it the right way or tell me another easier way? Edited by - Afterlife on October 6, 2001 10:53:41 AM

Share this post

Link to post
Share on other sites
Dracoliche    122
I think the formula you're looking for is:
a² = b² + c² - 2bc * cos(angle)
Where 'a', 'b' and 'c' are the side lengths, and the angle is opposite 'a'. Someone correct me if I'm wrong, it's pretty late

Argh -- what's the superscript tag? Rrgh. Let's see if the ANSI superscripted two works.

Edited by - Dracoliche on October 6, 2001 2:01:00 PM

Share this post

Link to post
Share on other sites
Afterlife    122
Oh yes indeed. I remembered the formula incorrectly :| Thanks

*need to find a school and fast*

Edit : also spotted another error in the code, but now it works

Edited by - Afterlife on October 6, 2001 2:59:00 PM

Share this post

Link to post
Share on other sites
Oluseyi    2103
The angle between two vectors is the scalar (dot) product of the vectors divided by the product of the vector

A *B = |A ||B |cos(theta)
cos(theta) = (A *B ) / (|A ||B |)

Assuming the player is at a point P, the mouse is at M and we choose a point up from the player U, your two vectors are
A = U - P
B = M - P

Just in case you''re rusty on vector math, the differences are:
U - P = (U.x - P.x, U.y - P.y);
M - P = (M.x - P.x, M.y - M.x);
The scalar product is:
A * B = (A.x * B.x) + (A.y * B.y)
And the magnitudes are:
|A| = sqrt( A.x2 + A.y2 );
|B| = sqrt( B.x2 + B.y2 );

Share this post

Link to post
Share on other sites