3D engine in 10 lines*

UPDATE – HTML 5 Canvas version now online

During my session at the Flash Gaming Summit, I showed a very simple 3D particle renderer to attempt to demystify the process of converting 3D into 2D.


Flash simple 3D particle renderer

Click and drag.

The actual code that converts from 3D to 2D is easy! First you have to figure out how much you have to resize things depending on how far away they are. (ie what their z position is).

newscale = f/(f+z);

Where f is a notional field of view. Changing this will change how wide the (virtual) camera is. A good starting point would be 250. Then you multiply the 3D x and y positions by the newscale to get their 2D x and y positions.

x2d = x3d * newscale; 
y2d = y3d * newscale;

So that’s where we put our particle, in this case represented by a MovieClip that we also need to resize by our new scale :

clip.scaleX = clip.scaleY = newscale;

And then the final thing we need to do is sort by the z position so that particles in front appear above particles in the background.

particles.sortOn("z", Array.DESCENDING | Array.NUMERIC); 
for(var i:int = 0; i< particles.length;i++)
{
	particle = particles[i];
	particleClip.setChildIndex(particle.clip, i); 
}

There’s some other stuff in there too, to create the depth of field blur and also the bitmap trails, but have a look and see what you can do with it.

Download the source code for simple 3D engine.

* I haven’t actually counted the number of lines. I’m guessing it’s about 10. :-)

Bookmark and Share

Related posts:

  1. New improved cacheAsBitmap!
  2. Flash Sparkler
  3. A cacheAsBitmap vs superCacheAsBitmap demo
  4. MovieClip.transform.matrix experiments…
  5. HTML5 Canvas 3D particles

Tags:

8 Responses to “3D engine in 10 lines*”

  1. [...] – case:MobileDesign! モバイルサイトのデザイン紹介ブログfc2:1 3D engine in 10 lines* | Seb Lee-Delisleはてブ:8 [...]

  2. [...] 3D engine in 10 lines* – Seb Lee-Delisle’s 3D Particle code from FGS preso [...]

  3. Nice bokeh :)
    Not sure I would use the word “engine”, more a nice pair of wind screen wipers…

  4. James Penman says:

    This is great! I spend too much time working on long custom scripts for commercial projects. I love seeing how efficiently some effects can be implemented. This little ‘engine’ is a fun starting point for a weekend “play” project. Thanks Seb!

    - James

  5. [...] Tutorials / Guides « 3D engine in 10 lines* [...]

  6. Cody says:

    i love your games. some are dumb but addicting. i think lunar lander 3d was amzing. top 10 online games i played

Leave a Reply

Bad Behavior has blocked 1363 access attempts in the last 7 days.