Game Development Reference
In-Depth Information
addEventListener(Event.ENTER_FRAME, updatePointer, false, 0,
true);
function updatePointer(e:Event) {
var angle:Number = Math.atan2(mouseY - pointer.y,
mouseX - pointer.x);
pointer.rotation = angle * (180 / Math.PI);
}
On every frame (30 times per second at our current frame rate),
the angle of the pointer relative to the mouse position is updated.
There is a fair amount going on in these two lines, so let
'
s look at
them one at a time.
var angle:Number = Math.atan2(mouseY - pointer.y, mouseX - pointer.x);
Remember we learned that if we know two sides of the triangle,
we could use that information to find out any of the angles. In this
case, we know the difference in x and y between the mouse cursor
and the pointer clip. These constitute the two shorter sides of a right
triangle
x
a straight line drawn between the pointer and mouse would
be the hypotenuse of this triangle. This is illustrated in Fig. 11.7 .
In the figure, A represents the angle we
A °
'
re interested in, as we
y
the imaginary hypotenuse.
This makes x distance the adjacent side to the angle, and y distance
the opposite side. Recall the formula for the tangent of an angle:
tan A = opp/adj . To determine A , we need to use the arctangent for-
mula: A =arctan( opp/adj ). In ActionScript, there are two ways to
implement arctangent
want the pointer to basically
look down
Figure 11.7 The distance
between the mouse cursor
and the registration point
of the pointer clip forms a
triangle.
they are the atan() and atan2() methods of
the Math class. The first expects to receive one value, assuming you
have already divided the opposite side by the adjacent. The second
one performs this step for you and is, thus, more commonly used (at
least by me); pass it the opposite side first, followed by the adjacent
side. In our case, the opposite side is the difference in the y value of
the mouse cursor and the y position of the pointer. Likewise, the adja-
cent side is the difference in x values of the cursor and the pointer.
We now have the angle represented by A in Fig. 11.7 . However, this
angle (and all angles returned by the arc functions in ActionScript) is
in radians ,not degrees . The rotation property of the pointer is assigned
in degrees, so we need to know how to convert one unit to the other.
Arc length = radius
A Quick Explanation of Radians and Pi
You already know that sum of all angles of a triangle is 180
Figure 11.8 When the
length of an arc on a circle
is equal to the circle ' s
radius, the value of the
angle formed is 1 radian.
°
,and
that of a circle is 360
, exactly double. A single radian is the value
of the angle created when a slice of the circumference of a circle is
equal to the circle
°
'
s radius; Figure 11.8 illustrates this.