Box2D: tutorial for the absolute beginners

This is a tutorial about Box2D dedicated to the absolute beginners.

I received a lot of request asking for this, so here we go.

What is Box2D

Box2D is a feature rich 2d rigid body physics engine, written in C++ by Erin Catto.

There is a Flash version called Box2DFlashAS3, but among Flash developers it’s called Box2D as well, that you can download from this link.

Being a Flash porting, we will use AS3 to make our project, instead of C++ as required by the original library.

Once you downloaded and unpacked the zip file in a folder, this is what you will get:

You are now ready to begin

Your first Box2D experiment

Start Flash and create a new AS3 Flash file and call it (example) demo.fla. Save it in the same folder you used to unzip Box2D package. Also in your properties panel assign the Class name to (example) demo, this way:

Now create a new actionscript file, call id demo.as and save it in the same folder.

Your folder now should look this way:

it’s time to edit demo.as

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class demo extends Sprite {
		public var the_world:b2World;
		var time_count:Timer=new Timer(1000);
		public function demo() {
			var environment:b2AABB = new b2AABB();
			environment.lowerBound.Set(-100.0, -100.0);
			environment.upperBound.Set(100.0, 100.0);
			var gravity:b2Vec2=new b2Vec2(0.0,10.0);
			the_world=new b2World(environment,gravity,true);
			var debug_draw:b2DebugDraw = new b2DebugDraw();
			var debug_sprite:Sprite = new Sprite();
			addChild(debug_sprite);
			debug_draw.m_sprite=debug_sprite;
			debug_draw.m_drawScale=30;
			debug_draw.m_fillAlpha=0.5;
			debug_draw.m_lineThickness=1;
			debug_draw.m_drawFlags=b2DebugDraw.e_shapeBit;
			the_world.SetDebugDraw(debug_draw);
			var final_body:b2Body;
			var the_body:b2BodyDef;
			var the_box:b2PolygonDef;
			the_body = new b2BodyDef();
			the_body.position.Set(8.5, 13);
			the_box = new b2PolygonDef();
			the_box.SetAsBox(8.5, 0.5);
			the_box.friction=0.3;
			the_box.density=0;
			final_body=the_world.CreateBody(the_body);
			final_body.CreateShape(the_box);
			final_body.SetMassFromShapes();
			addEventListener(Event.ENTER_FRAME, on_enter_frame);
			time_count.addEventListener(TimerEvent.TIMER, on_time);
			time_count.start();

		}
		public function on_time(e:Event) {
			var final_body:b2Body;
			var the_body:b2BodyDef;
			var the_box:b2PolygonDef;
			the_body = new b2BodyDef();
			the_body.position.Set(Math.random()*10+2, 0);
			the_box = new b2PolygonDef();
			the_box.SetAsBox(Math.random()+0.1,Math.random()+0.1);
			the_box.friction=0.3;
			the_box.density=1;
			final_body=the_world.CreateBody(the_body);
			final_body.CreateShape(the_box);
			final_body.SetMassFromShapes();
		}
		public function on_enter_frame(e:Event) {
			the_world.Step(1/30, 10);
		}
	}
}

Lines 2-5: some commons Flash libraries used to make the demo

Lines 6-9: Box2D libraries… it’s not that important at the moment to know everything about them… they’re just some libraries

Line 11: Declaring the_world variable, b2World type. b2World is the the main object to deal with the Box2d engine. It stores all the joints and bodies, handles listeners and is responsible for stepping through the simulation.

Line 14: Declaring the_environment, b2AABB type. The physics environment generated by Box2D is not infinite, and b2AABB is the container of such environment. Think about it as a bounding box. Inside this bounding box, the world is ruled by Box2D physics.

Lines 15-16 : Defining the upper and lower corners of the environment bounding box, in meters. 1 meter = 30 pixels. So our box has sides made by 6000 pixels. They’re pretty too much for a single-screen project, but if you are using scrolling, it could be useful to set up a big environment. For more information about pixels and meters refer to Understanding pixels and meters with Box2D and how to select an object with mouse – part 2.

Line 17: Declaring gravity variable, b2Vec2 type. b2Vec2 is a vector with x and y components.

Line 18: Starting up the world: the constructor has three parameters: environment, the worldAABB bounding box, gravity the world gravity vector, and a boolean set to true to improve performance by not simulating inactive bodies.

And now you created the world. Next time I’ll explain the rest of the script

Anyway, this is the result

And this is the source code to download.

I hope this will help you start playing with Box2D.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers