Create a polygon in Flash or Adobe AIR using Box2D.

By | February 5, 2011

The below function creates a polygon in the shape of a triangle.
Please call the debugdraw function inside your update method to view the results.
Make sure you import the Box2D classes into your file.

public function init():void
{
	 debug_draw();
	 addEventListener(Event.ENTER_FRAME, update);
	 createTriangle();
}


 public function createTriangle():void
 {
	 var fd : b2FixtureDef = new b2FixtureDef();
	 var initVel : b2Vec2 = new b2Vec2();
	 var bodyDef:b2BodyDef= new b2BodyDef();
	 var shape : b2PolygonShape = new b2PolygonShape();
	 bodyDef.type = b2Body.b2_dynamicBody;
	 bodyDef.position.Set(4.446215, 3.649402);
	 bodyDef.angle = 0.000000;
	 var polygon1 : b2Body = world.CreateBody(bodyDef);
	 initVel.Set(0.000000, 0.000000);
	 polygon1.SetLinearVelocity(initVel);
	 polygon1.SetAngularVelocity(0.000000);

	 var arr : Vector. = new Vector.();
	 arr[0] = new b2Vec2(-0.980080, 2.374502);
	 arr[1] = new b2Vec2(-0.980080, -1.187251);
	 arr[2] = new b2Vec2(1.960159, -1.187251);
	 shape.SetAsVector(arr,3);
	 fd.shape = shape;
	 fd.density = 0.30;
	 fd.friction = 0.300000;
	 fd.restitution = 0.600000;
	 fd.filter.groupIndex = 0;
	 fd.filter.categoryBits = 65535;
	 fd.filter.maskBits = 65535;
	 polygon1.CreateFixture(fd);
}


public function debug_draw():void
{
	 var debug_draw:b2DebugDraw = new b2DebugDraw();
	 var debug_sprite:Sprite = new Sprite();

	 /** Use this instead of addChild() ********/

	 var ui:UIComponent = new UIComponent();
	 ui.addChild(debug_sprite);
	 this.addElement(ui);

	 /*****************************************/
	 //addChild(debug_sprite);
	 debug_draw.SetSprite(debug_sprite);
	 debug_draw.SetDrawScale(world_scale);
	 debug_draw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
	 debug_draw.SetFillAlpha(0.5);
	 world.SetDebugDraw(debug_draw);
}

public function update(e:Event) : void
{
	 //We need to do this to simulate physics

	 world.Step(m_timestep,m_iterations,10);
	 for (var bb:b2Body=world.GetBodyList(); bb; bb=bb.GetNext())
	 {
		 if (bb.GetUserData() is Sprite)
		 {
			 bb.GetUserData().x=bb.GetPosition().x * 30;
			 bb.GetUserData().y=bb.GetPosition().y * 30;
			 bb.GetUserData().rotation=bb.GetAngle() * 180 / Math.PI;
		 }
	 }
	 world.DrawDebugData();
}

Leave a Reply

Your email address will not be published. Required fields are marked *