Game Development Reference
In-Depth Information
of constantly following the cursor, the pointer will only pursue the
mouse when it is within a certain distance.
var speed:Number = 5; //PIXELS PER FRAME
var interestDistance:Number = 150; //PIXELS
addEventListener(Event.ENTER_FRAME, updatePointer, false, 0,
true);
function updatePointer(e:Event) {
if (getDistance(mouseX, mouseY, pointer.x, pointer.y) >
interestDistance) return;
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)
>
Math.abs(ySpeed))
pointer.y += ySpeed;
}
function getDistance(x1:Number, y1:Number, x2:Number,
y2:Number):Number {
return Math.sqrt(Math.pow((x2-x1),2) + Math.pow((y2-y1),2));
}
The first variable we add is interestDistance , or the number of
pixels within which the pointer becomes
in the mouse
cursor. At the beginning of updatePointer ,wealsoaddacondition
to check if the distance between the two is greater than the amount
we specified. We do this by introducing a new function called
getDistance . If you remember any basic geometry from school, you
interested
ll
probably recognize this method as the distance formula .However,it
is also a variation of the Pythagorean theorem. Recall that
'
c 2
a 2
b 2
=
+
where a and b are sides of a triangle. To find c ,werewritethe
function as follows:
q
ð
a 2
b 2
c
=
+
Þ
In our case, a and b represent the differences in x and y ,
respectively. If we replace these variables with our actual values, it
looks like as follows:
q
ðð
2
2
distance
=
x 2
x 1
+ ð
y 2
y 1
Þ
Þ
Þ
Search Nedrilad ::




Custom Search