Reputation: 7739
How can I find the Angle of a line between two points in actionscript 3.
I have an object that dynamically animates out arrows, given the points that represent start, elbows, and then end point.
I need the angle of the line to rotate the arrow at the tip to accurately point with the current segment being drawn
I can easily get the angle for right angled lines by detecting if one axis is 0 but need the angle of any line between two points.
I'm familiar with getting the Points for a line e.g. draw a 100px line at 47 degrees:
var length:Number = 100;
var angle:uint = 48
graphics.lineTo(Math.cos(angle) * length, Math.sin(angle) * length);
but am struggling to get the angle from the line:
what I need is
given start point and end point of a line, what is the angle of the line.
many thanks for any and all suggustions
Upvotes: 2
Views: 4436
Reputation: 9461
Everyone is suggesting formulas using Math.atan(), giving caveats for 0 cases in the denominator. There's a whole function that already does this -- it's Math.atan2().
Just pass in an X and a Y value, and it gives you an angle. No special cases -- just coordinates. As usual, the return value is in radians, from -pi to +pi.
Upvotes: 5
Reputation: 137188
You're on the right lines way there with your formula for getting the end point of the line. You just need to invert the equation:
tan(theta) = opposite / adjacent
Which gives:
angle = arctan(opposite / adjacent)
Where the opposite is the height (y) and adjacent is the length (x).
Be careful as this breaks down when the adjacent is zero (divide by zero) and arctan will raise an exception for zero itself, so you need to trap the special cases of the line being vertical or horizontal.
As Miky D points out the angle is in radians, but you'll probably need it in that form for calculating the angle of the arrow head anyway.
Upvotes: 1
Reputation: 55760
The formula for the angle (also called the slope of the line) is as follows:
angle = Math.atan((y2 - y1) / (x2 - x1))
Where: (x1,y1) are the coordinates of the first point (start of line) and (x2,y2) are the coordinates of the second point (end of line)
Also, note that angle is returned in radians so if you need to get the angle in degrees you need to multiply by 180 and divide by PI:
angleInDegrees = angle * 180/Math.PI;
Upvotes: 1