我在管理孩子的容器時遇到了一些麻煩。事實是,它有很多孩子,他們的y座標非常隨機。如何在AS3中重新訂購我的容器的孩子
無論如何,我可以通過y座標來排列它們,下部位於前面,後面位於後面?
這是我能用2「for」做的事嗎?
謝謝您的幫助^^
我在管理孩子的容器時遇到了一些麻煩。事實是,它有很多孩子,他們的y座標非常隨機。如何在AS3中重新訂購我的容器的孩子
無論如何,我可以通過y座標來排列它們,下部位於前面,後面位於後面?
這是我能用2「for」做的事嗎?
謝謝您的幫助^^
//the number of elements in our component
var count:int = numElements;
var elements:Array = [];
//load all the elements of the component into an Array
for (var i:int=0; i<count; i++) {
elements[i] = getElementAt(i);
}
//sort the Array elements based on their 'y' property
elements.sortOn("y", Array.NUMERIC);
//re-add the element to the component
//in the order of the sorted Array we just created.
//When we add the element using 'addElement' it will
//be added at the top of the component's displaylist
//and will automatically be removed from its original position.
for (i=0; i<count; i++) {
addElement(elements[i]);
}
這是用於Spark組件。你可以用mx組件完成同樣的事情,使用getChildAt()
和addChild()
而不是getElementAt()
和addElement()
這聽起來像你想的堆疊順序相對於y
進行排序。
您可以使用此方法:
addChildAt(child:DisplayObject, index:int)
其中零的指數代表的顯示列表的底部,並numChildren - 1
代表頂部。
詳細信息請參考AS3的語言參考:flash.display.DisplayObjectContainer
謝謝你,但你可以更詳細嗎?因爲y是隨機創建的,所以我不知道索引的值。 –
當然!它看起來像其他人已經打敗了我。實際上,您必須將子元素放入數組中,對y進行排序,然後使用排序數組中的各個索引對DisplayObject進行重新排序。 – Peter
這裏假設你的容器被命名爲container
,並在相同的範圍存在的代碼(未經測試):
//prepare an array
var sortArray:Array = [];
//put the children into an array
for(var i:int = 0; i < container.numChildren; i++) {
sortArray[i] = container.getChildAt(i);
}
//get a sorting function ready
function depthSort(a:MovieClip,b:MovieClip):int
{
return a.y - b.y;
}
//sort the array by y value low -> high
sortArray.sort(depthSort);
//loop through the array resetting indexes
for(i = 0; i <sortArray.length; i++) {
container.setChildIndex(sortArray[i],i);
}
好像同時想);這是兩天以來的第二次。 – RIAstar
雖然你整個人都很整潔。 – shanethehat
當然var元素:Array = [count];是錯誤的,它應該是 var elements:Array = new Array(count); 但它也沒用,它也會像下面這樣工作: var elements:Array = []; –
這是超古老的,但你是對的。固定 – RIAstar