Game Development Reference

In-Depth Information

In order to do this, we need to think of the speed as the hypotenuse

of an imaginary triangle. We also already know the angle of the

triangle we

re interested in, because we just used arctangent to solve

it. With this information in hand, we can use the sine and cosine

functions to find the adjacent and opposite sides of this triangle, or

the
x
and
y
components, respectively.

'

var xSpeed:Number = Math.cos(angle) * speed;

var ySpeed:Number = Math.sin(angle) * speed;

Once we have these two speeds, we can simply apply them to

the
x
and
y
positions of the pointer to move it. In its simplest form,

that code would look like as follows:

pointer.x += xSpeed;

pointer.y += ySpeed;

However, if you were to leave the code like this, you would find

that the pointer would start to move erratically when it got very

close to the mouse. This is because while trying to get as close to

the cursor as possible, it continues to

its target and

will appear to bounce back and forth endlessly. To circumvent this

behavior, we need to check to see if the pointer is close enough to

the mouse so that it can stop moving. Doing so will employ

another method of the Math class,
abs()
. This method is known in

English as the
absolute-value
function. When given a number,

either positive or negative, it returns the
unsigned
value of that

number; Math.abs(4) = 4, Math.abs(

“

jump over

”

7)=7,etc.Inourexample,

we want to know whether the distance between the cursor and the

pointer is greater than the distance the pointer is trying to travel.

Sincewecan

−

'

t know whether difference between the cursor

'

s

position and the pointer

s position will result in a negative number,

we use the absolute value of the number for our calculation to

ensure it is always positive. We also apply the function for the

xSpeed
and
ySpeed
variables because there are situations where

they could be negative as well.

'

if (Math.abs(mouseX - pointer.x)
>
Math.abs(xSpeed)) pointer.x

+= xSpeed;

if (Math.abs(mouseY - pointer.y)

>

Math.abs(ySpeed)) pointer.y

+= ySpeed;

If you compile the SWF, you will see that this code causes the

pointer to follow the mouse around the screen, always pointing

toward it. While this logic is not what most people would consider

intelligence
, it is a form of AI.

Let

'

s look at one more example that will give the pointer a little

more

Open MouseFollowDistance.fla to follow along.

Continuing on our previous examples, we once again have a clip

named pointer and some code in the first frame. However, instead

“

personality.

”