Flash 3d Cube automatic sorting the displayList
Date: 9 June 2010I came across a small issue when creating a 3d object in the flash cs4 ide environment.
When you creata a cube from 6 panes and you want to rotate it on it's x, y and or z axil the following problem occurs:
As you can once the cube is rotated the panes' z-index get's distorted.
To fix this problem you have to calculate every frame and sort the display list according
to it's z position.
Lee Brimelow came with an easy SimpleZSorter class, which worked fine in some occasions, unfortunately not for me.
The problem with the above solution is that it uses the z position, instead of using the observer's point of view.
So I came up with a simple solution
The following example demonstrates this:
This example has a small sorting issue, this is because it's loaded into this blogpost, which gives it some problems
And the code that made it possible:
function autoZSort($cube:DisplayObjectContainer):void {
var faces:Array = [];
var i:int;
var curMid:Vector3D;
var pp:PerspectiveProjection = root.transform.perspectiveProjection;
observerPos.x = pp.projectionCenter.x;
observerPos.y = pp.projectionCenter.y;
observerPos.z = -pp.focalLength;
var mc:DisplayObject;
for(i = 0; i < $cube.numChildren; i++){
mc = $cube.getChildAt(i);
curMid = mc.transform.getRelativeMatrix3D($cube.root).position.clone();
faces.push({mc: mc, dist: Math.sqrt(Math.pow(curMid.x - observerPos.x, 2) + Math.pow(curMid.y - observerPos.y, 2) + Math.pow(curMid.z-observerPos.z, 2)) });
}
faces.sortOn("dist", Array.NUMERIC | Array.DESCENDING);
for (i = 0; i < faces.length; i++) {
cube.setChildIndex(faces[i].mc, i);
}
}You can download the .fla here (56 kb)