Create a Flash Ball game with visual from above – Box2D version

Read all posts about "" game

After the old AS2 example and the Flare3D example published some days ago, it’s time to show you how to create a Flash Ball game with visual from above using Box2D.

Let’s jump directly to source code:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class box2dball extends Sprite {
		private var world:b2World=new b2World(new b2Vec2(0,0),true);
		private var worldScale:int=30;
		public var theBall:b2Body;
		private var left,right,up,down:Boolean=false;
		public function box2dball() {
			debugDraw();
			addTrack(100,240,200,480);
			addTrack(540,240,200,480);
			addTrack(320,-100,640,200);
			addTrack(320,580,640,200);
			addBall(100,100);
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyD);
			stage.addEventListener(KeyboardEvent.KEY_UP,onKeyU);
		}
		private function debugDraw():void {
			var debugDraw:b2DebugDraw = new b2DebugDraw();
			var debugSprite:Sprite = new Sprite();
			addChild(debugSprite);
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
			debugDraw.SetFillAlpha(0.5);
			world.SetDebugDraw(debugDraw);
		}
		private function addTrack(xOrigin:Number,yOrigin:Number,xSize:Number,ySize:Number):void {
			var box:b2BodyDef= new b2BodyDef();
			box.position.Set(xOrigin/worldScale,yOrigin/worldScale);
			var square:b2PolygonShape = new b2PolygonShape();
			square.SetAsBox(xSize/2/worldScale, ySize/2/worldScale);
			var boxFixture:b2FixtureDef = new b2FixtureDef();
			boxFixture.shape=square;
			boxFixture.isSensor=true;
			var boxBody:b2Body=world.CreateBody(box);
			boxBody.CreateFixture(boxFixture);
			boxBody.SetLinearVelocity(new b2Vec2(0,5));
		}
		private function addBall(xOrigin:Number,yOrigin:Number):void {
			var ball:b2BodyDef= new b2BodyDef();
			ball.userData=new Object();
			ball.userData.name="ball";
			ball.type=b2Body.b2_dynamicBody;
			ball.position.Set(xOrigin/worldScale, yOrigin/worldScale);
			ball.linearDamping=1.01;
			var circle:b2CircleShape=new b2CircleShape(15/worldScale);
			var ballFixture:b2FixtureDef = new b2FixtureDef();
			ballFixture.shape=circle;
			ballFixture.friction=10;
			ballFixture.density=1;
			ballFixture.restitution=1;
			theBall=world.CreateBody(ball);
			theBall.CreateFixture(ballFixture);
		}
		private function onKeyD(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case 37 :
					left=true;
					break;
				case 38 :
					up=true;
					break;
				case 39 :
					right=true;
					break;
				case 40 :
					down=true;
					break;
			}
		}
		private function onKeyU(e:KeyboardEvent):void {
			switch (e.keyCode) {
				case 37 :
					left=false;
					break;
				case 38 :
					up=false;
					break;
				case 39 :
					right=false;
					break;
				case 40 :
					down=false;
					break;
			}
		}
		private function manageForces():void {
			var force:b2Vec2=new b2Vec2(0,0);
			if (left) {
				force.Add(new b2Vec2(-10,0));
			}
			if (right) {
				force.Add(new b2Vec2(10,0));
			}
			if (up) {
				force.Add(new b2Vec2(0,-10));
			}
			if (down) {
				force.Add(new b2Vec2(0,10));
			}
			if (force.x||force.y) {
				theBall.ApplyForce(force,theBall.GetWorldCenter());
			}
		}
		private function update(e:Event):void {
			manageForces();
			world.Step(1/30,10,10);
			world.ClearForces();
			world.DrawDebugData();
			x=320-theBall.GetWorldCenter().x*worldScale;
			y=240-theBall.GetWorldCenter().y*worldScale;
		}
	}
}

and let’s see the interesting lines:

Line 9: being a game with visual from above, there’s no gravity, that’s why the gravity vector in the constructor is set to a null vector.

Lines 24-33: this function, called at line 14, manages the debug draw. For more information about debug draw check Understanding Box2D debug draw.

Lines 34-45: this function simply adds a box to the world, as you have seen a million times. Just notice line 41 where isSensor property is set to true. If you don’t know what is a Box2D sensor, check Box2D Flash game creation tutorial – part 2.

Lines 46-61: this function will add the ball. Nothing new in this piece of code too, but note how I simulate air friction setting linearDamping property greater than 1 at line 52

Lines 94-95: according to the arrow key(s) being pressed, a different force is applied to the ball.

And here is the result:

Tap arrow keys to move the ball. Try to keep it inside the track. At the moment we don’t check if the ball is inside the track. We’ll do it in next step, when we’ll finish the prototype.

Download the source code.

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

214 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
// 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