Creation of a Flash Stabilize! clone using Box2D – part 1

Read all posts about "" game

In Triqui’s picks 1 I told you Stabilize! is a good game to clone using Box2D.

And I would use this post to focus on another thing too… it’s about recycling.

I mean… once you code for a while, or follow developer’s blogs like this one providing a lot of source codes, probably most of the stuff you need has already been written here and there.

In this case, the script we are going to modify is Drawing boxes on the fly in Box2D.

You will see we can make the whole game simply changing the original script step by step.

Coding this way will speed up your learning curve because you are starting from a working project so you don’t have to worry about the overall environment, and you can focus on small changes.

In this first step, we’ll just spend a couple of words about the balance bar.

It’s made up with a static object (the fulcrum) and a dynamic one (the bar).

In order to work, the density of the bar should be quite greater than the one of the falling boxes, or you’ll risk to lose the bar once the first box falls on it.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class stabilize extends Sprite {
		public var m_sprite: Sprite = new Sprite();
		public var m_world:b2World;
		public var initX:Number=0.0;
		public var initY:Number=0.0;
		public var drawing:Boolean=false;
		public function stabilize() {
			var gravity:b2Vec2=new b2Vec2(0,9.8);
			var worldAABB:b2AABB = new b2AABB();
			worldAABB.lowerBound.Set(-1000,-1000);
			worldAABB.upperBound.Set(1000,1000);
			m_world=new b2World(worldAABB,gravity,true);
			m_sprite = new Sprite();
			addChild(m_sprite);
			debug_draw();
			AddBox(250/30,350/30,10/30,10/30,0);
			AddBox(250/30,350/30,200/30,10/30,20);
			addEventListener(Event.ENTER_FRAME,Update);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
			stage.addEventListener(MouseEvent.MOUSE_UP,mouseReleased);
		}
		public function mousePressed(e:MouseEvent) {
			//Store initial X and Y position
			initX=e.localX;
			initY=e.localY;
			drawing=true;
		}
		public function mouseMoved(e:MouseEvent) {
			if (drawing) {
				//Simply draw the "ghost" of the box we are about to add
				graphics.clear();
				graphics.beginFill(0xFF0000,0.5);
				graphics.drawRect(initX,initY,e.localX-initX,e.localY-initY);
			}
		}
		public function mouseReleased(e:MouseEvent) {
			graphics.clear();
			drawing=false;

			//Coordinates of bottom-right of box (when drawing from left to right)
			var finalX:Number=e.localX;
			var finalY:Number=e.localY;

			//Correct if drawing from right to left
			if (finalX0&&boxHalfHeight>0) {
				AddBox((finalX-boxHalfWidth)/30,(finalY-boxHalfHeight)/30,boxHalfWidth/30,boxHalfHeight/30,1);
			}
		}
		/*
		NOTE: AddBox takes the _x,_y and halfwidth and halfheight parameters
		in METRES not PIXELS. This means when you call this function, always
		DIVIDE a pixel size by 30 to get it in meteres.
		*/
		public function AddBox(_x:Number,_y:Number,_halfwidth:Number,_halfheight:Number,density:Number) {
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.position.Set(_x,_y);
			var boxDef:b2PolygonDef = new b2PolygonDef();
			boxDef.SetAsBox(_halfwidth,_halfheight);
			boxDef.density=density;
			boxDef.friction=0.3;
			boxDef.restitution=0.2;
			var body:b2Body=m_world.CreateBody(bodyDef);
			body.CreateShape(boxDef);
			body.SetMassFromShapes();
		}
		public function Update(e:Event) {
			//We need to do this to simulate physics
			m_world.Step(1/30,10);
		}
		public function debug_draw() {
			var dbgDraw:b2DebugDraw = new b2DebugDraw();
			var dbgSprite:Sprite = new Sprite();
			m_sprite.addChild(dbgSprite);
			dbgDraw.m_sprite=m_sprite;
			dbgDraw.m_drawScale=30;
			dbgDraw.m_alpha=1;
			dbgDraw.m_fillAlpha=0.5;
			dbgDraw.m_lineThickness=1;
			dbgDraw.m_drawFlags=b2DebugDraw.e_shapeBit;
			m_world.SetDebugDraw(dbgDraw);

		}
	}
}

And this is the result:

Draw boxes with your mouse and see how does the bar react.

No need to download anything, simply cut/paste the script you can find at Drawing boxes on the fly in Box2D.

Next time, we’ll manage “true” crates.

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