Game Development Reference
In-Depth Information
The
distance
variable is calculated with a standard geometric equation, as shown in Figure 4-14.
We converted the equation to AS3, but it is the exact same calculation.
Figure 4-14.
Using a distance equation to determine the
xunits
and
yunits
values
Now that we know the
distance
of the line, we can calculate how many frames it will take to get
from the start point to the end point if we know the speed the
Shot
needs to travel. Luckily, we
already know the speed.
moves = Math.floor(Math.abs(distance/speed));
Finally, we can get the exact number of pixels to move each frame by dividing
(endLocation.x -
x)
by
moves
and
(endLocation.y - y)
by
moves
.
xunits = (endLocation.x - x)/moves;
yunits = (endLocation.y - y)/moves;
The nice thing about doing this calculation once is that, for the rest of the time this
Shot
exists in
the game, it only has to do some simple arithmetic to move. All necessary values have already
been calculated. There are other ways to calculate a vector and move a sprite, but this is one of
the best methods we have found that will move an object on a line to reach an exact point. We
will discuss a more general-purpose algorithm to move an object when we talk about the
Enemy
class.
Now we must finish up by actually getting the
ShotGif
graphic
BitmapData
from the library and
attaching it to an instance of
Bitmap
. (Remember, in Flex, you need to uncomment the Flex code
and comment out the Flash code).
//***** Flex *****
//imageBitmapData = new ShotGif().bitmapData;
//***** Flash *****
imageBitmapData = new ShotGif(0,0);
image = new Bitmap(imageBitmapData);