Here is an example where a collection of balls in the 3D space is being rotated. Clearly, for each view we have to place the right ball on the right depth as some balls are in front of others.
The example is based on a 3D engine in ActionScript 3 that we presented in our Simple 3D Drawing in Flash CS3 tutorial in Advanced section. We only comment on the part of the code pertinent to depths management.
Download
- Flash CS3 file depths_2.fla
The Part of Code Relevant to Depths Sorting
function renderView(t:Number,p:Number):void {
//......................
/*
We are storing the distance of each ball from the camera together with the number of the ball is an array, distArray.
We sort the the array with respect to the ball's distance from the camera from the back to the front.
*/
for(i=0;i < numBalls;i++){
dist=Math.sqrt(Math.pow(fLen-posNewArray[i][0],2)+Math.pow(posNewArray[i][1],2)
+Math.pow(posNewArray[i][2],2));
distArray[i]=[dist,i];
}
distArray.sort(byDist);
for(i=0;i < numBalls;i++){
dispArray[i]=[fLen/(fLen-posNewArray[i][0])*posNewArray[i][1],
-fLen/(fLen-posNewArray[i][0])*posNewArray[i][2]];
}
for(i=0;i < numBalls;i++){
/*
distArray has been sorted with respect to the distance of each ball from the camera
from back to front; that is, from lower depths to higher depths.
We place each consecutive ball on the highest possible depth in spBoard, soBoard.numChildren-1.
This way each next ball appears in front of the previous balls.
*/
spBoard.setChildIndex(this["ball_"+distArray[i][1]],spBoard.numChildren-1);
this["ball_"+i].scaleX=fLen/(fLen-posNewArray[i][0]);
this["ball_"+i].scaleY=fLen/(fLen-posNewArray[i][0]);
this["ball_"+i].alpha=2*fLen/(fLen-posNewArray[i][0])-1;
this["ball_"+i].x=dispArray[i][0];
this["ball_"+i].y=dispArray[i][1];
}
}
function byDist(v:Array,w:Array):Number {
if (v[0] > w[0]){
return -1;
} else if (v[0] < w[0]){
return 1;
} else {
return 0;
}
}
On the next page, a drag and drop example.













