Math Question: Calculate an Angle of a line

Started by mode7, Fri 13/01/2012 23:03:34

Previous topic - Next topic

mode7

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
Code: ags

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!!!


DoorKnobHandle

The easiest and fastest way to do this is to avoid trigonometry altogether and use simple vector math instead.

Code: ags

// 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;

Khris

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));

SMF spam blocked by CleanTalk