Game Development Reference
In-Depth Information
imageBitmapData = new PlaneGif(0,0);
angle = 90;
break;
case DIR_RIGHT:
//***** Flex *****
//imageBitmapData = new PlaneRightGif().bitmapData;
//**** Flash *****
imageBitmapData = new PlaneRightGif(0,0);
angle = 45;
break;
case DIR_LEFT:
//***** Flex *****
//imageBitmapData = new PlaneLeftGif().bitmapData;
//**** Flash *****
imageBitmapData = new PlaneLeftGif(0,0);
angle=135;
break;
}
image = new Bitmap(imageBitmapData);
addChild(image);
finished = false;
}
Now that we have values for
angle
and
speed
, we can calculate the next x and y values to move
the
Enemy
. Recall that a vector needs both direction and velocity. Both angle and speed fulfill
those requirements for
Enemy
.
The first thing we need to do is to change the value we have for
angle
into radians. Radians are a
standard unit of measurement used in trigonometry to calculate the values for sine and cosine of
an angle. It just happens that we can use sine and cosine to help us calculate
nextLocation
for
the
Enemy
. A radian is equal to about 57.3 degrees, but for our game, you don't really need to
know that. All you need to know is how to convert
angle
to
radians
which can be done like this:
radians = angle * Math.PI / 180;
To find the values for
nextLocation
, we will use sine and cosine with the
radians
value to find the
change in
x
(
Math.cos()
) and the change in
y
(
Math.sin()
) given a velocity (
speed
). We then add
those values back the current values for
x
and
y
, and we have the next location to move.
public function update():void {
if (y < endLocation.y) {
var radians:Number = angle * Math.PI / 180;
nextLocation.x = x + Math.cos(radians) * speed;
nextLocation.y = y + Math.sin(radians) * speed;
} else {
finished = true;
}
}
While the description for this calculation might seem complicated, the good news is that this code
is nearly plug and play among different platforms and programming languages. Once you know
the basics how to find the
nextLocation
values using radians, sine, and cosine, the rest can be
easily converted on nearly any platform. The advantage of this method over the point-to-point
method is that we could easily change the angle of the
Enemy
and have it move in a different
direction. The rest of the functions in enemy remain essentially unchanged from the
Shot
class.