Categories

# 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.

[kml_flashembed publishmethod=”dynamic” fversion=”10.0.0″ useexpressinstall=”true” movie=”/wp-content/uploads/manual/2010/Particles3D.swf” width=”500″ height=”350″ targetclass=”flashmovie”]

[/kml_flashembed]
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.

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

## 9 replies on “3D engine in 10 lines*”

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

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

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

hehe yeah you’re probably right 🙂

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

Very glad I could help, enjoy the play time 🙂

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

Codysays:

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

[…] Rendering 3D See it live and get code hereor learn about it here […]