Using Matrix3D objects for reordering display

As mentioned previously, the layering order of display objects in the display list determines the display layering order, regardless of their relative z-axes. If your animation transforms the properties of display objects into an order that differs from the display list order, the viewer might see display object layering that does not correspond to the z-axis layering. So, an object that should appear further away from the viewer might appear in front of an object that is closer to the viewer.

To ensure that the layering of 3D display objects corresponds to the relative depths of the objects, use an approach like the following:

  1. Use the getRelativeMatrix3D() method of the Transform object to get the relative z-axes of the child 3D display objects.

  2. Use the removeChild() method to remove the objects from the display list.

  3. Sort the display objects based on their relative z-axis values.

  4. Use the addChild() method to add the children back to the display list in reverse order.

This reordering ensures that your objects display in accordance with their relative z-axes.

The following code enforces the correct display of the six faces of a 3D box. It reorders the faces of the box after rotations have been applied to the it:

public var faces:Array; . . . 
 
public function ReorderChildren() 
{     
    for(var ind:uint = 0; ind < 6; ind++) 
    { 
        faces[ind].z = faces[ind].child.transform.getRelativeMatrix3D(root).position.z; 
        this.removeChild(faces[ind].child); 
    } 
    faces.sortOn("z", Array.NUMERIC | Array.DESCENDING); 
    for (ind = 0; ind < 6; ind++) 
    { 
        this.addChild(faces[ind].child); 
    } 
}

To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The application files are in the Samples/ReorderByZ folder.