我的目标是每次点击舰船都射出一颗子弹。实际上,如果我点击一次,子弹就会射出,但如果我在第一颗子弹离开屏幕之前点击两次,第一颗子弹就会停止(它没有消失,只是停止),第二颗子弹就会射出。
public var ship:Ship = new Ship();
public var bullet:Bullet = new Bullet();
stage.addChild(ship);
ship.addEventListener(MouseEvent.CLICK, shoot);
function shoot(e:MouseEvent):void
{
stage.addEventListener(Event.ENTER_FRAME, bulletflies);
}
function bulletflies(e:Event):void
{
stage.addChild(bullet);
bullet.y -= 5;
}
将项目符号设置为自己的类,并让该类自己迭代移动:
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);
}
}
}
在Ship类中,将shoot函数更改为:
function shoot(e:MouseEvent):void {
this.addChild(new Bullet(this));
}
将Ship作为一个类,Bullet作为另一个类是很好的。这样,每个对象都照顾它的self。此外,如果你最终有了EnemyBullet
,那么你可以开始使用继承和多态性(我敢打赌,一旦你学会了它们,你会喜欢它们)。
这是因为你只有一个项目符号。
你可以创建一个项目符号数组,所以修改
public var bullet:Bullet = new Bullet();
public var bullets:Array = [];
,
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);
}
}
——编辑——
回复你的评论
我不喜欢每个子弹都有自己的ENTER_FRAME
在ship.addEventListener(MouseEvent.CLICK, shoot);
下添加一行stage.addEventListener(Event.ENTER_FRAME, bulletflies);
移除b.addEventListener(Event.ENTER_FRAME, bulletflies);
并将事件处理程序更改为:
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);
}
}
}