Basic Filler engine with Box2D – part 1

Read all posts about "" game

Do you remember Filler?

Filler

In Filler, your goal is simple: fill 2/3 of the level. To create a filler ball, press down. It will grow until you release the mouse button, it hits another filler ball, or a bouncing ball runs into it.

I am showing you the first part, the creation of the filler ball by pressing down the mouse, with no collision detection while you are creating the ball.

The code is mainly taken from Drawing circles on the fly in Box2DfleshMaker version, but uses movieclips for the balls (so I removed the debug draw) and has a different way of creating circles on the fly.

This is the script:

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 colorballz extends Sprite {
		public var m_dbgSprite;
		public var m_world:b2World;
		public var m_phys_scale:Number = 30;
		public var m_timestep:Number = 1.0/30.0;
		public var m_iterations:Number = 10.0;

		//initial box coordinates when we first press mouse down
		public var initX:Number = 0.0;
		public var initY:Number = 0.0;
		public var drawing:Boolean = false;
		public var b:b2Body;

		//
		public var the_ball:ball;
		public function colorballz() {
			/*
			A Box2D world needs three parameters: a b2AABB, gravity
			and a Booleand deciding whether or not to let bodies sleep
			when they are not being simulated.
			This saves CPU so should always be left on :)
			*/

			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);

			//Add Our Ground
			AddStaticBox(250/m_phys_scale,510/m_phys_scale,250/m_phys_scale,10/m_phys_scale);
			AddStaticBox(250/m_phys_scale,-10/m_phys_scale,250/m_phys_scale,10/m_phys_scale);
			AddStaticBox(-10/m_phys_scale,250/m_phys_scale,10/m_phys_scale,250/m_phys_scale);
			AddStaticBox(510/m_phys_scale,250/m_phys_scale,10/m_phys_scale,250/m_phys_scale);

			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;
			the_ball = new ball();
			the_ball.x = mouseX;
			the_ball.y = mouseY;
			the_ball.width = 1;
			the_ball.height = 1;
			addChild(the_ball);
			drawing = true;
		}
		public function mouseMoved(e:MouseEvent) {
			if (drawing) {
				the_ball.x = mouseX;
				the_ball.y = mouseY;
			}
		}
		public function mouseReleased(e:MouseEvent) {
			drawing = false;
			addCircle( mouseX,  mouseY, the_ball.width/2,the_ball);
		}
		public function addCircle(_x:Number, _y:Number, _radius:Number,ballclip:ball) {
			var bd:b2BodyDef = new b2BodyDef();
			var cd:b2CircleDef = new b2CircleDef();
			var area:Number = Math.floor(_radius*_radius*Math.PI/25)/100;
			// area is the % of the entire stage filled by the circle
			// the entire stage area is 500*500 = 250000 pixels
			// circle area is radius*radius*PI
			// so the % is radius*radius*PI*100/250000
			cd.radius = Math.abs(_radius)/m_phys_scale;
			cd.density = 2;
			cd.restitution = 0.7;
			cd.friction = 2;
			bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
			bd.userData = ballclip;
			b = m_world.CreateBody(bd);
			b.CreateShape(cd);
			b.SetMassFromShapes();
		}
		public function AddStaticBox(_x:Number,_y:Number,_halfwidth:Number,_halfheight:Number) {
			var bodyDef:b2BodyDef = new b2BodyDef();
			bodyDef.position.Set(_x,_y);
			var boxDef:b2PolygonDef = new b2PolygonDef();
			boxDef.SetAsBox(_halfwidth,_halfheight);
			boxDef.density = 0.0;
			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
			if (drawing) {
				the_ball.width+=2;
				the_ball.height+= 2;
			}
			m_world.Step(m_timestep,m_iterations);
			for (var bb:b2Body=m_world.m_bodyList; bb; bb=bb.m_next) {
				if (bb.m_userData is Sprite) {
					bb.m_userData.x=bb.GetPosition().x * 30;
					bb.m_userData.y=bb.GetPosition().y * 30;
					bb.m_userData.rotation=bb.GetAngle() * 180 / Math.PI;
				}
			}
		}
	}
}

There are some inline comments, and there is nothing that new in the code.

Here it is the result:

Click and hold to make the ball grow, release to create it.

And this is the source.

Next step we will see something new: how to make some objects to be affected by gravity and some other not to be affected.

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