Game Development Reference
In-Depth Information
Now we will need a couple variables to hold the amount to move
Shot
on the (x, y) plane on each
frame. We will calculate and hold those variables in
xunits
and
yunits
.
private var xunits:Number;
private var yunits:Number;
Because we are going to calculate the next place to move our sprites before we actually move
them, we need a place to store the next positions to move the
Shot
. We hold these in another
Point
class named
nextLocation
.
private var nextLocation:Point;
Now, we need to set a
speed
for the
Shot
(we default to 15 pixels per frame) and create a variable
that holds the number of
moves
the
Shot
will make before it is finished. We also need a variable
we can check from
Game
to see if the
Shot
has finished moving. We do that with the
finished
variable.
private var speed:int = 15;
private var moves:int = 0;
public var finished:Boolean;
Finally, if we are building this game in Flex, we will need to embed the
ShotGif
graphic. You will
need to uncomment this code to make it work:
/*
//**Flex Framework Only
[Embed(source = "assets/flakassets.swf", symbol="ShotGif")]
private var ShotGif:Class;
*/
The constructor for this function is quite simple. It takes two points
(startX, startY)
and
(endX,
endY)
and stores them in our instance variables:
startLocation
and
endLocation
. We also
initialize the
nextLocation
instance of
Point
so we can use it later. Then we call
init()
where the
most interesting stuff will happen.
public function Shot (startX:Number, startY:Number, endX:Number, endY:Number)
{
startLocation = new Point(startX,startY);
endLocation = new Point(endX,endY);
nextLocation = new Point(0,0);
init();
}
We just defined the very basics of the
Shot
class. Now, we will fill it out will all the necessary
functions. The good news is that even though we have multiple moving objects in Flak Cannon,
most of the objects use similar code, so some of this code will need to be described once.
The
init()
function is where we will calculate
xunits
and
yunits
for the
Shot
. The first thing we
are going to do is to calculate the distance between the start point
startLocation
(when the
Shot
starts), and the end point
endLocation
, which is the middle of the crosshairs.
public function init():void
{
x = startLocation.x;
y = startLocation.y;
var xd:Number = endLocation.x - x;
var yd:Number = endLocation.y - y;
var distance:Number = Math.sqrt(xd*xd + yd*yd);