Playing with Box2DFlashAS3

Talking about Actionscript 3, Box2D and Flash.

Some time ago I told you to watch Box2DFlashAS3 physics engine.

I dont’ know if you did it, but I did. While the original Box2D project come to 2.0.0 version, the AS3 porting is “still” at 1.4.3, but soon it will be upgraded.

So I think it’s absolutely time to play with this library.

While I won’t be able to provide a full tutorial before some days, I made an interesting prototype in only 58 lines, brackets included.

package {
	import flash.display.*;
	import flash.events.*;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class theclass extends Sprite {
		var body_def:b2BodyDef;
		var shape_def:b2BoxDef;
		public var the_world:b2World;
		public function theclass() {
			var container:b2AABB = new b2AABB();
			container.minVertex.Set(0.0, 0.0);
			container.maxVertex.Set(500.0, 400.0);
			the_world = new b2World(container, new b2Vec2(0, 300.0), true);
			body_def = new b2BodyDef();
			shape_def = new b2BoxDef();
			shape_def.extents.Set(250,10);
			shape_def.friction = 1;
			body_def.position.Set(250,390);
			body_def.AddShape(shape_def);
			body_def.userData = new floor();
			body_def.userData.width = 500;
			body_def.userData.height = 20;
			addChild(body_def.userData);
			the_world.CreateBody(body_def);
			addEventListener(Event.ENTER_FRAME, render);
			addEventListener(MouseEvent.CLICK, mouse_handler);
		}
		private function mouse_handler(event:MouseEvent):void {
			body_def = new b2BodyDef();
			shape_def = new b2BoxDef();
			shape_def.extents.Set(Math.floor(Math.random()*15)+15,Math.floor(Math.random()*15)+15);
			shape_def.friction = 1;
			shape_def.density = 1;
			shape_def.restitution = 0.2;
			body_def.position.Set(Math.random()*400+50,0);
			body_def.AddShape(shape_def);
			body_def.userData = new crate();
			body_def.userData.width = shape_def.extents.x * 2;
			body_def.userData.height = shape_def.extents.y * 2;
			addChild(body_def.userData);
			body_def.userData.gotoAndStop(Math.floor(Math.random()*6)+1);
			the_world.CreateBody(body_def);
		}
		public function render(e:Event):void {
			the_world.Step(1/30, 10);
			for (var x:b2Body = the_world.m_bodyList; x; x = x.m_next) {
				if (x.m_userData is Sprite) {
					x.m_userData.x = x.m_position.x;
					x.m_userData.y = x.m_position.y;
					x.m_userData.rotation = x.m_rotation * 57.2957795;
				}
			}
		}
	}
}

And the result is really interesting, and virtually impossible to achieve without the library… just click on the floor and see what happens…

I think it’s time to start learning AS3 with this interesting library… meanwhile you can download the source code with the last version of Box2DFlashAS3 library.