Any smart people out there who can tell me why this function Im working on to automatically sort the depths of objects placed on the 3D plane is only working intermittently? It seems to work every second or third iteration?
function zsort(h){
var zpos=[] //array to store Z positions
var mc,mcZpos
for(var i=0; i<h.numChildren-1; i++){
mc = h.getChildAt(i);
mcZpos=(mc.z - (Math.sin(mc.rotationX) * mc.height/2)) //get lowest Z point based on X rotation
zpos.push([mcZpos, mc])
}
zpos.sort()
for(i in zpos){
h.setChildIndex(zpos[i][1], h.numChildren-1)
}
}
Is getChildAt(i) reliable? IE does it return the same order each time it runs or is it based on depth?
EDIT: looking at the manual suggests that it’s probably the latter so I guess I’ll need to make my own array ordered by the time the sprites were added to the parent and work from there. Is there a better way?
This class works, could probably be optimized but it works and should be a good start:
http://blog.theflashblog.com/?p=470
http://code.google.com/p/leebrimelow/source/browse/#svn%2Ftrunk%2Fas3%2Fcom%2Ftheflashblog%2Futil3d
Since you’re having issues with your algorithm it’s probably just the best solution (both to get operational faster and to learn by example not by re-inventing the wheel). If you want to do anything other than this basic kind of 3d positioning, go with a library, namely away3d.
All the best. 🙂