【问题标题】:AS3: How to control which MovieClip is displayed over whichAS3:如何控制哪个 MovieClip 显示在哪个之上
【发布时间】:2015-07-18 18:31:02
【问题描述】:
我正在制作一个游戏,其中一些敌人在屏幕右侧生成,然后向屏幕左侧移动。为了获得一点变化,敌人在 y 轴上随机生成的方式略有不同。
问题:
所以我知道,最后添加的 MovieClip 会显示在其他 MovieClip 的顶部。但我需要一种方法,以便无论何时添加,y 轴上较低的 MovieClip 始终显示在 y 轴上较高的 MovieClip 之上。
原因是否则它会混淆游戏中的水平错觉,因为在 y 轴上较高的 MovieClip 应该看起来比在 y 轴上较低的 MovieClip 看起来更远。
我希望我说得通。提前致谢!
【问题讨论】:
标签:
actionscript-3
flash
movieclip
flash-cs6
【解决方案1】:
您需要根据y 位置对它们进行排序,然后根据排序顺序在父级中设置它们的索引:
此函数将获取容器/父级的所有子级,并根据y 位置对它们进行排序。
function sortAllZ(container:DisplayObjectContainer):void {
//build an array of all the objects:
var list:Vector.<DisplayObject> = new Vector.<DisplayObject>();
var i:int = container.numChildren;
while(i--){
list.push(container.getChildAt(i));
}
list.sort(sortZ);
for(var i:int=0;i<list.length;i++){
container.addChild(list[i]);
}
}
function sortZ(a:DisplayObject, b:DisplayObject):Number {
return a.y - b.y;
}
由于您可能会在每一帧都运行此代码(假设您的对象的 y 位置随时间而变化),因此保留您想要排序的所有对象的数组/向量会更有效。 (而不是每次要排序时都重新创建一个新的)。如果是这种情况,您可以这样做:
//where list is your vector/array, and container is the parent of items
function sortAll(){
//sort the vector/array using the custom sort method defined below
list.sort(sortZ);
//now loop through that array and add the children in that order
for(var i:int=0;i<list.length;i++){
container.addChild(list[i]);
}
}
//if you are using an array and not a vector, take out the :DisplayObject type declarations
function sortZ(a:DisplayObject, b:DisplayObject):Number {
return a.y - b.y;
}