29a.ch experiments by Jonas Wagner

Box2Dflash Version 2.0 ported Javascript

Written by

Please note that this is experimental code! If you use this please let me know and give Erin Catto and me some credit.

Some weeks ago I wrote a script to convert version 2.0.2 of Box2DFlash to Javascript. I hesitated to release it because it is basically one big nasty hack that just happens to work. But as I got a few requests for it so I decided to release it. Please let me know if you do something with it. :)



You can see a demo of it in action here. You can click to trigger an explosion. On my notebook the demo runs fluidly in chrome. In firefox 3.5 it is pretty slow. In the current nightly it runs smooth as well. So I guess firefox is slowly catching up. Oh and just forget about IE.


At first thought this conversion would be trivial as both actionscript and javascript are dialects of ECMAScript. Well, I was wrong. Nevertheless I continued to follow my regex based approach, basically trying to ram my head through a wall. After a few attempts I succeeded to convert Box2DAS3 to javascript. It had a nasty bug tough. Two solid cubes were able to penetrate each other when the fell on their edges. The reason? ActionScript supports 'properties'. I didn't know about this and the conversion script does not support it. In the end I fixed the few properties in the translated code by hand because I was to lazy to add support for getters and setters to the conversion script. Now it seems to work pretty well. Please keep in mind, this is not a generic actionscript to javascript compiler, it's just a script that happens to work for box2dflash.

The explosions in the demo are simulated by shooting out a few tracer particles with a high density and velocity. The benefit over just applying an impulse to each object is that the strength of the impulse is proportional to the surface area. Also the force of the explosion will to some extend be redirected to the side by the floor. When using this in production code you would probably want to destroy this tracer particles after their first collision or a few seconds.

Please keep in mind, I'm not an expert on the subject. There are probably better and faster ways to approximate this than my crude way of using tracer particles (Navier-Stokes in javascript anybody? ;) ). Maybe I'll try to do some fluid dynamics on the gpu using webgl some day. It would be cool for sure.

Compiled Script

I compiled a single file version of the script using googles closure compiler. box2d.js.

Complete Zip

The zip file contains the actionscript source, the conversion script and a patch to fix some of the things the conversion script misses. box2d2.zip




I didn't write any. But you can use the documentation of box2dflash.

comments powered by Disqus