There are a few ways to do this. If you just want a projectile to have a lifespan (i.e., it exists for 3 seconds then disappears), you can make a simple timer in Projectile.update()
or use an Alarm
.
If you desire a distance, you’ll need to know both where the Projectile
started and where it currently is. Since you already know where it is (Projectile.x
and Projectile.y
), you just need to keep track of where it started.
public class Projectile extends Entity
{
/** The initial x-location of the Projectile. */
protected var _initialX:Number;
/** The initial y-location of the Projectile. */
protected var _initialY:Number;
/** The distance the Projectile may travel. */
protected const MAX_DISTANCE:Number = 100;
public function Projectile(initialX:Number, initialY:Number)
{
// Store the initial location.
_initialX = initialX;
_initialY = initialY;
// Perform any other initialization during construction.
// The x and y location will be set by Entity's constructor via super().
super(initialX, initialY);
}
override public function update():void
{
// Perform any movement and collision code required by the Projectile.
// Check the distance traveled.
if (FP.distance(_initialX, _initialY, x, y) >= MAX_DISTANCE)
{
// The Projectile has traveled its maximum distance.
destroy();
}
}
public function destroy():void
{
// Perform any destruction tasks, like playing a sound or explosion.
}
}
With a setup like this, you can simplify your shoot function slightly.
public function shoot(x:Number,y:Number, facing:int, kind:int):Projectile
{
var p:Projectile = new Projectile(x, y);
p.direction = facing;
p.projectileSprite.frame = kind;
FP.world.add(p);
return p;
}