Tag Archives: 3D

Flash CS4 3D – Depth Management

i’ve been playing around with the 3D tools in Flash 10/CS4, with half a mind to completely redo our cube-mapped memory game Two By Two with an actual 3D cube. (Currently, the game uses a series of skewed planes to fake the 3D effect.)

The good news is that CS4 does support 3D, although some people on the web are calling it 2.5D for one particular reason: the DisplayObjects that you transform and translate are unaware of each other, and do not exist in the same 3D space.

Here’s what that means: you can have two planes sitting next to each other. Depth-wise, PlaneA is in front of PlaneB. You move PlaneA backwards along the z axis, and it never swaps depths behind PlaneB. It’s as if the two clips are entirely autonomous and exist in their own little 3D worlds. Which they do.

note: you’ll need to be running the Flash Player 10 plugin to view these examples. Get it HERE.

[SWF]http://www.untoldentertainment.com/blog/labs/3d/depthProblem/depthProblem.swf, 550, 400[/SWF]

This becomes a big problem when you need things to look natural. Check out this Flash coder’s experiment with a 3D world and a camera:

Flash 3D World with Messed Up Depth

This is fine if all of your game characters have X-Ray vision, i suppose.

The floors and the walls are placed correctly, but they all show through each other. i had the exact same problem when i tried building a cube from MovieClips. Placing the clips was very easy, but the depth problem baffled me. i knew that i had to loop through all the cube faces and re-order them based on their z properties, but i didn’t know how to do that, since localToGlobal only supports x/y coordinates.

It turns out you have to actually write your own depth manager if you want to build any kind of 3D object and have it display correctly. i found just the code i needed here on Drew Cummins’s blog:


i’m a big enough man to admit that at one o’clock in the morning last night, i didn’t fully grasp how this code did what it did. Happily, it worked. You can see the difference in cube rendering below. The cube on the left applies Drew’s depth management routine.

Thanks, Drew!

[SWF]http://www.untoldentertainment.com/blog/labs/3d/cube_depthManagement/cube_comparison.swf, 550, 400[/SWF]

Additional notes: there is a (possibly deliberate?) type-o in Drew’s code. One of the loops is missing a minus operator on its iteration decrementor (i-), so watch out for that.

You may also have to rely on the ADDED_TO_STAGE event, as Drew’s code threw me an error when doc.stage was null. This can happen when you try to fire code before an object actually exists on the stage.