The distance of each element within the scene is determined by a single value, known as the z depth. The z depth value is calculated using the average position of each vertex that makes up an element along the camera's local coordinate Z-axis. An easy way to visualize the camera's local space is to imagine that the camera is sitting at the origin, and is looking directly towards the positive end of the Z-axis. This is illustrated in the following image:
The coordinates of the vertices that make up the triangle have been noted in the image. These coordinates are in the camera's local space. To calculate the z depth, we take the Z components of these coordinates (which are 110, 100, and 90), and average them to give a final value of 100.
This single value of 100 is then used as the z depth the 2D representation of the triangle, even though the depth of the individual vertices ranges from 90 to 110. Sorting the 3D object elements by their z depths can lead to inconsistencies when the single averaged z depth value does not accurately represent a drawing primitive's relative position within the scene.
To demonstrate a situation where the 3D object elements are not sorted correctly, let's create a new example called ZSorting
. In the initScene()
function we will create two triangles, angled so that one appears to overlap the other from the camera's viewpoint.
package { import away3d.primitives.Triangle; public class ZSorting extends Away3DTemplate { public function ZSorting() { super(); } protected override function initScene():void { super.initScene(); camera.z = 0; var triangleA:Triangle = new Triangle( { x: -30, y: 0, z: 500, rotationY: -5, yUp: false, bothsides: true } ); var triangleB:Triangle = new Triangle( { x: 30, y: 0, z: 499, rotationY: 60, yUp: false, bothsides: true } ); scene.addChild(triangleA); scene.addChild(triangleB); } } }
The following image is a top-down view of the scene. Triangle B has a slightly smaller z depth than Triangle A, and the triangles do not intersect.
The following image shows how the two triangles are drawn when the application is run:
From the top-down view of the scene, it is clear that the triangle on the right (Triangle B) should appear behind the one on the left (Triangle A). But because Triangle B has a smaller z depth than Triangle A, Triangle B is considered to be in front of Triangle A. This results in Triangle B being drawn last, over the top of Triangle A. Here is a perfect example of where a single average z depth does not accurately reflect the actual depth of the 3D objects in the scene.