Categories
Articles

Box2D 2.1 Flash Hello World Falling Boxes

I decided it was time to try out Box2DFlash, a free 2D physics engine for Flash that works in both Flash and Flex Builder 4.

I found most examples were for version 2.02 and earlier and there is now a version 2.1a (alpha) which it appears everyone is treating as a release. I downloaded the 2.1a version and immediately was struggling to find good starting examples since the developer documentation is not ready for 2.1a save scant update notes.

I started out with a video tutorial from Todd Kerpelman who did a great job for anyone starting cold turkey. His examples are for Box2D version 2.0 and he has a note that he will update for 2.1. I also converted his Puggle version of Peggle Nights.

Todd may hold out revising videos as I read forum rumors that more major code revisions are possible with Box2D and judging from this update, there is no tolerance for maintaining backwards compatibility other than use the older version. Todd’s videos are longish and would be served better if he added code to copy for each video. However his explanations of Bxo2d in the videos are extremely helpful.

I found by taking Todd’s work and a Box2d 2.1a example by Allan Bishop, I was able to revise Todd’s example in 2.1a. Allan’s example is more basic than is Todd’s example. I also would like to point out Allan has several more 2.1a version examples that are intriguing that I intend to explore.

You can build this with the free Flex SDK by using the code in the src folder and be sure to include a path to the Box2DFlash 2.1a library. For Flash CS3 and later versions, you need to create a Flash Document in the src folder and set the document class to HelloWorldFallingBoxes01 and then add a library path to the Box2DFlash 2.1a code or SWC if you created one. For your convenience the Flash CS4 example download is included.

You can download Box2dFlash to work with the source, get the API documentation and more examples. I included a SWC library for version 2.1a in the example downloads so you will know they work despite what happens at Box2dFlash.org.

This article shows the code for the Flex project.

Application Class – HelloWorldFallingBoxes01
All the code is contained in this class except for the Box2d library. The applicationCompleteHandler creates the Box2D world. The world contains a floor and left and right walls. It also will contain a bunch of falling rectangles that I am calling falling boxes. It sets a debug feature so we can visualize the physic data computed and starts an ENTER_FRAME event to make updates.

All the measurements are in meters so there is ratio PIXELS_TO_METERS constant on line 60 to handle that conversion when you want to think in pixels.

The Box2D world works with “center” registration points and so the measurements for the container, in this case the Flash movie, are provided as constants on line 44 and 48 to create the offsets.

The MAX_WORLD_BODIES constant on line 68 is used as an upper limit in adding the falling boxes. The walls, floor and falling boxes are referred to as bodies in Box2D. The MAX_WORLD_BODIES constant along with the NEXT_BOX_IN_INTERVAL constant on line 56 will control the addition of falling boxes.

<?xml version="1.0" encoding="utf-8"?>
<!--
/**
* Demonstration of Box2D 2.01a dropping boxes into container.
* */
--><s:Application 
   		xmlns:fx="http://ns.adobe.com/mxml/2009" 
		xmlns:s="library://ns.adobe.com/flex/spark" 
		xmlns:mx="library://ns.adobe.com/flex/mx" 
		applicationComplete="applicationCompleteHandler(event)"
		width = "550"
		height = "400"
		>
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import Box2D.Collision.Shapes.b2PolygonShape;
			import Box2D.Collision.b2AABB;
			import Box2D.Common.Math.b2Vec2;
			import Box2D.Dynamics.b2Body;
			import Box2D.Dynamics.b2BodyDef;
			import Box2D.Dynamics.b2DebugDraw;
			import Box2D.Dynamics.b2FixtureDef;
			import Box2D.Dynamics.b2World;
			import mx.events.FlexEvent;
			/**
			 * Properties for background
			 * @see background_bc
			 */
			private static const backgroundColor:Number = 0x333333;
			/**
			 * The Box2D world
			 */
			private var _world:b2World;
			/**
			 * Frames per second. 
			 */
			private const FPS:uint = 30;
			/**
			 * Movie width 
			 */
			private const SWF_WIDTH:int = 550;
			/**
			 * Movie height
			 */
			private const SWF_HEIGHT:int = 400;
			/**
			 * Wall thickness
			 */
			private const WALL_THICKNESS:int = 5;
			/**
			 * Interval, in frames, between adding boxes to fall.
			 */
			private const NEXT_BOX_IN_INTERVAL:int = 5;
			/**
			 * Ratio of pixels to meters. 30 is a defacto standard.
			 */
			private static const PIXELS_TO_METER:Number = 40;
			/**
			 * Number of frames until next box is added.
			 * */
			private var _nextBoxIn:int = 0;
			/**
			 * Maximum bodies including boxes, floor and walls.
			 * */
			private const MAX_WORLD_BODIES:int = 80;
			/**
			 * Handler for applicationComplete event. Setup world and begin animation.
			 * */
			protected function applicationCompleteHandler(event:FlexEvent):void
			{
				trace("applicationCompleteHandler(...)");
				// Setup the world
				setupWorld();
				// Create walls and floor
				createWallsAndFloor();
				// Visualize with debugDraw
				setupDebugDraw();
				// Listen to ENTER_FRAME event.
				addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			}

[ad name=”Google Adsense”]
This section updates the world. The world updates with the Step method shown on line 89.

There is also logic on line 111 – 118 to add falling boxes at the top of the animation using randomized sizes and positions we will see in the addBox() method later. Here the coding is simply trying to time the frame intervals when a new falling box is added and to deal with some of the new requirements in Box2D 2.1a for updating the world.

			/**
			 * Handler for ENTER_FRAME event.
			 * */
			private function enterFrameHandler(e:Event):void
			{
				updateWorld();
			}
			/**
			 * Update world. Add additional boxes.
			 * */
			private function updateWorld():void
			{
				//trace("Main.updateWorld(...)");
				// Box2D manual recommends 1/60 seconds 
				// set it to the SWF framerate
				var timeStep:Number = 1 / FPS;
				// velocityIterations and positionIteration with 10 being the 
				// suggested count for each. 
				// Fewer iterations boosts performances 
				// but comes at the cost of accuracy.
				var velocityIterations:int = 6;
				var positionIterations:int = 2;
				// Update the world
				_world.Step(timeStep, velocityIterations, positionIterations);
				// As of version 2.1 we must clear the forces.
				_world.ClearForces();
				// Reduce frame delay for adding box
				_nextBoxIn--;
				// Time to add another box
				if ( _nextBoxIn <= 0 && _world.GetBodyCount() < MAX_WORLD_BODIES)
				{
					addBox();
					// Reset the box frame delay
					_nextBoxIn = NEXT_BOX_IN_INTERVAL;
				}
				// Draw the debug data.
				_world.DrawDebugData();
			}

This function creates the world. The 2.1a b2Word constructor no longer requires a universe size. The constructor arguments are now down to two.

			/**
			 * Setup the world.
			 * */
			private function setupWorld():void
			{
				trace("Main.setupWorld()");
				// Define gravity. Y = 9.8 meters per second.
				var gravity:b2Vec2 = new b2Vec2( 0, 9.8);
				// Ignore sleeping babies
				var ignoreSleeping:Boolean = true;
				_world = new b2World( gravity, ignoreSleeping );
			}

[ad name=”Google Adsense”]
In the createFloor() method, the groundBody b2Body is created and represent the floor. Version 2.1a uses b2FixtureDef. You create fixture definition for material properties. You provide the shape to the fixture, and call b2Body.CreateFixture.

			/**
			 * Create the walls and floor.
			 * */
			private function createWallsAndFloor():void
			{
				trace("Main.createWallsAndFloor()");
				createFloor();
				createWalls();
			}
			/**
			 * Create the floor.
			 * */
			private function createFloor():void
			{
				trace("Main.createFloor()");
				// Define the ground body.
				var groundBodyDef:b2BodyDef= new b2BodyDef();
				// Set position
				groundBodyDef.position.Set(	(SWF_WIDTH / 2) / PIXELS_TO_METER, 
					(SWF_HEIGHT - WALL_THICKNESS) / PIXELS_TO_METER );
				// Factory design pattern to create the body.
				var groundBody:b2Body = _world.CreateBody(groundBodyDef);
				// Create our shape.
				var groundBox:b2PolygonShape = new b2PolygonShape();
				// Set the box dimensions. 
				// Width 1/2 of MovieClip less offset for left and right wall thicknesses 
				// Height = wall thickness.
				groundBox.SetAsBox( 
					( (SWF_WIDTH ) / 2) / PIXELS_TO_METER - ( WALL_THICKNESS * 2) / PIXELS_TO_METER, 
					WALL_THICKNESS / PIXELS_TO_METER);
				// Create a fixture definition for body
				var groundFixtureDef:b2FixtureDef = new b2FixtureDef();
				// Set shape
				groundFixtureDef.shape = groundBox;
				// Set density
				groundFixtureDef.density = 1;
				// Set friction 100%
				groundFixtureDef.friction = 1;
				// Create fixture
				groundBody.CreateFixture(groundFixtureDef);
			}

Creating the walls mirrors the code for creating the floor. The b2BodyDef is reused for both wall b2Body bodies because the word CreateBody method copies and does not provide a pointer to a b2BodyDef. There are computations for position and box sizes stand next to the floor.

			/**
			 * Create the walls.
			 * */
			private function createWalls():void
			{
				trace("Main.createWalls() - left wall");
				// Define the wall body.
				var wallBodyDef:b2BodyDef= new b2BodyDef();
				
				wallBodyDef.position.Set( WALL_THICKNESS / PIXELS_TO_METER, ( SWF_WIDTH - WALL_THICKNESS ) / PIXELS_TO_METER );
				// Factory design pattern to create the body.
				var leftWallBody:b2Body = _world.CreateBody(wallBodyDef);
				// Create shape.
				var leftWallBox:b2PolygonShape = new b2PolygonShape();
				// Set as a box.
				leftWallBox.SetAsBox(WALL_THICKNESS / PIXELS_TO_METER, ( SWF_WIDTH - WALL_THICKNESS )  / PIXELS_TO_METER);
				// Create a fixture definition for left and right wall bodies
				var wallFixtureDef:b2FixtureDef = new b2FixtureDef();
				// Set shape 
				wallFixtureDef.shape = leftWallBox;
				// Set density
				wallFixtureDef.density = 0;
				// Set friction 50%
				wallFixtureDef.friction = 0.5;
				// Set restitution to 30%
				wallFixtureDef.restitution = 0.3;
				// Create fixture
				leftWallBody.CreateFixture(wallFixtureDef);
				trace("Main.createWalls() - right wall");
				wallBodyDef.position.Set(
					545 / PIXELS_TO_METER, 
					( SWF_WIDTH - WALL_THICKNESS ) / PIXELS_TO_METER );
				// Factory design pattern to create the body.
				var rightWallBody:b2Body = _world.CreateBody(wallBodyDef);
				// Create our shape.
				var rightWallBox:b2PolygonShape = new b2PolygonShape();
				// Redefine shape
				wallFixtureDef.shape = rightWallBox;
				// Set as a box.
				rightWallBox.SetAsBox(
					WALL_THICKNESS / PIXELS_TO_METER, 
					( SWF_WIDTH - WALL_THICKNESS ) / PIXELS_TO_METER);
				// Create fixture
				rightWallBody.CreateFixture(wallFixtureDef);
			}

[ad name=”Google Adsense”]
The addBox method creates a new falling box. It follows the same code steps as the floor. Differences include that the boxBodyDef type is dynamic to allow for movement, the use of SetAsOrientedBox on line 238 instead of SetAsBox used for floor and walls. The SetAsOrientedBox allows for rotation. To get to the angle argument you need to provide a b2Vec2 center point.

Randomizing the box sizes and starting positions is included for some variety.

			/**
			 * Add a falling box.
			 * */
			private function addBox():void
			{
				trace("Main.addBox()");
				var boxBodyDef:b2BodyDef= new b2BodyDef();
				boxBodyDef.position.Set( 
					randomInt(15, 530) / PIXELS_TO_METER, 
					randomInt(-100, -50) / PIXELS_TO_METER );
				// Crates move.
				boxBodyDef.type = b2Body.b2_dynamicBody;
				// Here we can see the factory design pattern being used to create the body.
				var boxBody:b2Body = _world.CreateBody(boxBodyDef);
				// Create our shape.
				var boxShape:b2PolygonShape = new b2PolygonShape();
				// Randomize the crate size and convert to meters.
				var hx:Number = randomInt(5, 40) / PIXELS_TO_METER;
				var hy:Number = randomInt(5, 40) / PIXELS_TO_METER;
				// Set as an oriented box
				boxShape.SetAsOrientedBox(
					hx, 
					hy,
					new b2Vec2(hx / 2, hy / 2), 		     // Center
					(Math.random() * 360) * (Math.PI / 180)	// Rotation random degrees converted to radians
				);	
				
				// Create a fixture definition for crate
				var boxFixtureDef:b2FixtureDef = new b2FixtureDef();
				// Set shape
				boxFixtureDef.shape = boxShape;
				// Set density
				boxFixtureDef.density = 0.7;
				// Set friction 80%
				boxFixtureDef.friction = 0.8;
				// Set restitution to 30%
				boxFixtureDef.restitution = 0.3;
				// Create fixture
				boxBody.CreateFixture(boxFixtureDef);
			}

Here we have some utilities. First is the b2DebugDraw to make the physics data visual and a method to compute a random number from a range.

The b2DebugDraw is added to the SpriteVisualElement box2DContainer on line 265.

			/**
			 * Setup the b2DebugDraw
			 * */
			private function setupDebugDraw():void
			{
				trace("Main.setupDebugDraw()");
				var spriteToDrawOn:Sprite = new Sprite();
				box2DContainer.addChild(spriteToDrawOn);
				var debugDraw:b2DebugDraw = new b2DebugDraw();
				debugDraw.SetSprite(spriteToDrawOn);
				debugDraw.SetDrawScale(PIXELS_TO_METER);
				debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
				debugDraw.SetLineThickness(2.0);
				debugDraw.SetFillAlpha(0.6);
				_world.SetDebugDraw(debugDraw);
			}
			/**
			 * Return a random int from a range.
			 * @param lowVal  Start of the range.
			 * @param highVal  End of the range.
			 * @return Random int from lowVal to highVal
			 * */
			private function randomInt(lowVal:int, highVal:int):int
			{
				if ( lowVal <= highVal)
				{
					return (lowVal + Math.floor(Math.random() * ( highVal - lowVal + 1)));
				}
				else
				{
					throw (new Error("Main.randomInt(...) lowVal exceeds highVal"));
				}
			}

		]]>
	</fx:Script>

These are the Flex visual components. Simply a background using the BorderContainer and a the Flex 4 SpriteVisualElement to contain the b2DebugDraw.

	   <!--
	   Background for app 
	   --> 
	   <s:BorderContainer id = "background_bc"
						  width="{width}" height = "{height}"
						  
						  backgroundColor="{backgroundColor}">
		   
		   <!--
		   Container for the Box2D world
		   -->
		   <s:SpriteVisualElement id = "box2DContainer" />
	   </s:BorderContainer> 
</s:Application>

Leave a Reply