Adventure Game Studio

AGS Support => Advanced Technical Forum => Topic started by: mode7 on Fri 13/01/2012 23:03:34

Title: Math Question: Calculate an Angle of a line
Post by: mode7 on Fri 13/01/2012 23:03:34
Well this is more of a math question than a technical one. I still think it fits here best.

Basically I want to have a line which has a fixed origin and length to point towards the mouse pointer.
I already put everything together to the point that i only need to supply an angle for the line-pointing-thingy.

I found this formula which I used somewhere else which i think can be resolved to output the angle

mouse.x = originx + 'r'  * cos(angle)

will resolve to

cos(angle) = (mouse.x-originx) /r

//r is is the distance from he origin to the mousetip - calculated with the good old pythagoras and thats also where my math skills end



So my simple, yet probably naive, question is
How do I get the angle out of the the Cosinus

DAMN YOU TRIGONOMETRY!!!

Title: Re: Math Question: Calculate an Angle of a line
Post by: DoorKnobHandle on Fri 13/01/2012 23:35:50
The easiest and fastest way to do this is to avoid trigonometry altogether and use simple vector math instead.


// this code will give us a line that is 100 units long and points from line_origin to the mouse location

#define LINE_LENGTH 100


// create a vector from the line origin to the mouse cursor (vector_a_to_b = b - a)

float vector_x = mouse.x - line_origin_x;
float vector_y = mouse.y - line_origin_y;


// calculate the length of that vector and normalize it using the length

float vector_length = Maths.sqrt ( ( vector_x * vector_x ) + ( vector_y * vector_y ) );
vector_x = vector_x / vector_length;
vector_y = vector_y / vector_length;


// now that vector has a length of one unit, let's make it bigger again

vector_x = vector_x * LINE_LENGTH;
vector_y = vector_y * LINE_LENGTH;
Title: Re: Math Question: Calculate an Angle of a line
Post by: Khris on Sat 14/01/2012 11:16:48
Yeah, vector math is awesome :)

If you still need the angle however, that's were the Arc functions come in. Basically, ArcCos(Cos(angle)) = angle.
To calculate the angle of a vector, use Maths.ArcTan2(dy, dx).

It'll return something inside [-π, π], so to get a nice angle inside [0.0; 360.0], use a = Maths.RadiansToDegrees(Maths.ArcTan2(dy, dx));