Event flow in AS3 - Shoot a bullet
My goal is to shoot a bullet everytime I click on ship. What happens, in fact, is that If I click on it once, the bullet is shot, but if I click on it twice before the first bullet is off the screen, the first bullet literally stops(it does not disappear, only stops) and the second bullet is shot.
public var ship:Ship = new Ship();
public var bullet:Bullet = new Bullet();
stage.addChild(ship);
ship.addEventListener(MouseEvent.CLICK, shoot);
fu开发者_StackOverflow中文版nction shoot(e:MouseEvent):void
{
stage.addEventListener(Event.ENTER_FRAME, bulletflies);
}
function bulletflies(e:Event):void
{
stage.addChild(bullet);
bullet.y -= 5;
}
Set up the bullet as it's own class and have that class iterate the movement on it's own:
public class Bullet extends Sprite {
public function Bullet(ship:Ship) {
// this assumes that you've also set "Ship" up as it's own class
this.x = ship.x;
this.y = ship.y;
this.addEventListener(Event.ENTER_FRAME, this.enterFrameHandler);
}
private function enterFrameHandler(event:Event):void {
this.y -= 1;
// destroy this clip when it's outside of the stage - better mem managament
if(this.y < 0 || this.y > this.stage.stageHeight) {
this.removeEventListener(Event.ENTER_FRAME, this.enterFrameHandler);
this.parent.removeChild(this);
}
}
}
In your Ship class, change your shoot function to:
function shoot(e:MouseEvent):void {
this.addChild(new Bullet(this));
}
It's good to have the Ship as one class and Bullet as another. This way each object is taking care of it's self. Also, if you end up having EnemyBullet
then you can start using inheritance and polymorphism (I bet you'll like those once you learn them).
This is because you have only 1 bullet.
You can create an array of bullets, so change
public var bullet:Bullet = new Bullet();
to
public var bullets:Array = [];
Then,
ship.addEventListener(MouseEvent.CLICK, shoot);
function shoot(e:MouseEvent):void
{
var b:Bullet=new Bullet();
b.addEventListener(Event.ENTER_FRAME, bulletflies);
stage.addChild(b);
bullets.push(b);
}
function bulletflies(e:Event):void
{
e.currentTarget.y -= 5;
if(e.currentTarget.y < 0 || e.currentTarget.y > stage.height) {
stage.removeChild(e.currentTarget);
bullets.splice(bullets.indexOf(e.currentTarget), 1);
}
}
--EDIT--
In response to your comment
I don't like the idea of each bullet having it's own ENTER_FRAME
Add a line stage.addEventListener(Event.ENTER_FRAME, bulletflies);
under ship.addEventListener(MouseEvent.CLICK, shoot);
Remove b.addEventListener(Event.ENTER_FRAME, bulletflies);
and change the event handler to this:
function bulletflies(e:Event):void
{
for each(var b:Bullet in bullets) {
b.y -= 5;
if(b.y < 0 || b.y > stage.height) {
stage.removeChild(b);
//bullets.splice(bullets.indexOf(b), 1);
}
}
}
精彩评论