Game Development Reference
In-Depth Information
a full understanding
of the use of radians is not necessary to perform the math we need.
In fact, there is a very handy constant in math that will help us
convert between radians and degrees. It is known as Pi (pronounced
If this explanation is confusing, don
t worry
, and a nonrepeating decimal
number approximately equivalent to 3.141. It represents the number
of radians in a triangle, or half the number of radians in a circle.
Therefore, 180
), represented by the symbol
radians. To convert between radians and
degrees, we simply multiply a number of radians by 180/
is equal to
or a
number of degrees by
/180. Returning to our ActionScript example
from above, the next line of code does just that, using the Math.
PI constant.
pointer.rotation = angle * (180 / Math.PI);
If you test this FLA file, you will see that the pointer consistently
points in the direction of your cursor as you move it around the
screen. Now that we have this piece of functionality in place, let
add a layer of complexity. Suppose in addition to
mouse we wanted the pointer to also move toward the mouse until
it reaches the mouse
looking at
s x and y positions. If you open the example
MouseFollower.fla, you
ll see how we can accomplish this.
Initially, this example looks very much like the previous one,
except for a few extra lines of code. Let
s look at this additional
ActionScript now.
var speed:Number = 5; //PIXELS PER FRAME
addEventListener(Event.ENTER_FRAME, updatePointer, false, 0,
function updatePointer(e:Event) {
var angle:Number = Math.atan2(mouseY - pointer.y,
mouseX - pointer.x);
pointer.rotation = angle * (180 / Math.PI);
var xSpeed:Number = Math.cos(angle) * speed;
var ySpeed:Number = Math.sin(angle) * speed;
if (Math.abs(mouseX - pointer.x) > Math.abs(xSpeed))
pointer.x += xSpeed;
if (Math.abs(mouseY - pointer.y)
pointer.y += ySpeed;
ve added is a speed component. This defines
how many pixels the pointer should move per frame, in this case
the number of pixels is 5. In the updatePointer function, we
The first line we
ve also
added a few lines to perform this move. Since the speed is how
many pixels we want to move in a straight line, we need to convert
it into the amount we need to move in the x-axis and y-axis .
Search Nedrilad ::

Custom Search