简而言之,我有各种颜色的可点击对象。我希望这些颜色在单击后出现在我的占位符中(会有6个)。我目前已经设法进行编码,以便在单击任何颜色时将其放置在第一个占位符中。
我可以通过哪种方式编码以识别第一个占位符已被填充,而第二个占位符一旦被填充将成为目标?
最好先填满第6个,然后停下来,这样用户才能看到全部6个。
我正在考虑使用for循环之类的方法比较合适,但是我不确定该如何处理。
到目前为止,它看起来像这样:
//Placeholder
var placeHolder1:MovieClip = new MovieClip();
placeHolder1.x = 20;
placeHolder1.y = 245;
stage.addChild(placeHolder1);
//Placeholder2 (UNUSED CURRENTLY)
var placeHolder2:MovieClip = new MovieClip();
placeHolder2.x = 60;
placeHolder2.y = 245;
stage.addChild(placeHolder2);
//Click and select colours
var newBlue:cBlue = new cBlue();
numBlue.addEventListener(MouseEvent.CLICK, fBlue)
function fBlue(e:MouseEvent){
placeHolder1.addChild(newBlue);
}
var newRed:cRed = new cRed();
numRed.addEventListener(MouseEvent.CLICK, fRed)
function fRed(e:MouseEvent){
placeHolder1.addChild(newRed);
}
答案 0 :(得分:2)
首先,您可能想了解Arrays(或Vectors)。数组/向量是列表,因此您需要将所有占位符放入数组:
var placeHolders:Array = [placeHolder1, placeHolder2];
但是,由于创建占位符有一个公式,您可能希望循环执行此操作以使其 DRY er( D R 重复 Y 我们自己
此循环将创建10个占位符,并将它们添加到数组中:
var placeholders:Array = new Array();
for(var i:int=0; i < 10; i++){
var placeHolder = new Sprite(); //if your not using timelines, just use Sprite instead of MovieClip as it's less overhead
placeHolder.x = 20 * (i + 1); //i starts at 0, and goes to 9
placeHolder1.y = 245;
stage.addChild(placeHolder); //add it to the display list
placeholders.push(placeHolder); //add it to the array
}
现在(继续为DRY),将相同的事件侦听器附加到所有颜色按钮上:
numBlue.addEventListener(MouseEvent.CLICK, selectColor);
numRed.addEventListener(MouseEvent.CLICK, selectColor);
在该事件处理程序中,我将其称为“ selectColor”(请参见代码注释)
function selectColor(e:Event):void {
//get the first element in the array
var placeHolder:Sprite = placeholders.shift(); //shift removes the first item from the array, and returns it
placeHolder.addChild(e.currentTarget); //e.currentTarget refers to item that you attached the event listener to, in this case either numBlue or numRed
}
总而言之,这将获得数组中的第一个占位符,从数组中删除该项目,然后添加作为该占位符的子元素而被单击的颜色按钮。