每次运行程序时,我都会在舞台上添加一个牛仔。当我主持这个节目时,我希望舞台上有5个牛仔。我知道我可以复制并粘贴4次代码,但我想知道是否有一种更短、更快的方法可以做到这一点。
这是我的代码
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.display.Bitmap;
import flash.ui.Mouse;
import flash.events.MouseEvent;
/**
* ...
* @author Callum Singh
*/
public class Main extends Sprite
{
public var gun:crosshair;
public var cowboy:enemy;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
gun = new crosshair();
stage.addChild (gun);
addEventListener(Event.ENTER_FRAME, moveCrosshair);
cowboy = new enemy();
cowboy.x = Math.random() * 600;
cowboy.y = Math.random() * 400;
stage.addChild(cowboy);
cowboy.addEventListener(MouseEvent.CLICK, handleShoot);
}
private function moveCrosshair(e:Event):void
{
gun.x = mouseX -120;
gun.y = mouseY -115;
Mouse.hide();
}
private function handleShoot(e:MouseEvent):void
{
if (e.target == cowboy)
{
cowboy.visible = false;
}
}
}
}
虽然Iggy是正确的,但它不会像您基于代码的其余部分所期望的那样工作。如果不考虑,它仍然会得到5个牛仔,但只创建1个牛仔参考。cowboy
是一个类变量,执行他的代码只会在每次循环中覆盖牛仔变量。
你需要抓住每一个牛仔的例子。基本方法是将它们存储到Array或Vector中。您也可以通过名称引用它们(如果您正在设置的话)。从上面的代码来看,这里只是将这两个选项都考虑在内的调整。
public class Main extends Sprite
{
public var gun:crosshair;
public var cowboys:Array; // Array to hold all your cowboys
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
gun = new crosshair();
stage.addChild (gun);
addEventListener(Event.ENTER_FRAME, moveCrosshair);
cowboys = new Array();
for(var i:uint = 0; i < 5; ++i) {
var cowboy:enemy = new enemy();
cowboy.x = Math.random() * 600;
cowboy.y = Math.random() * 400;
cowboy.name = "cowboy" + i; // assuming that your enemy class extends DisplayObject types
stage.addChild(cowboy);
cowboy.addEventListener(MouseEvent.CLICK, handleShoot);
cowboys.push(cowboy);
}
}
Basic for循环应该可以完成任务。
for(var i:uint = 0; i < 5; ++i) {
cowboy = new enemy();
cowboy.x = Math.random() * 600;
cowboy.y = Math.random() * 400;
stage.addChild(cowboy);
cowboy.addEventListener(MouseEvent.CLICK, handleShoot);
}