“Hundreds” Flash game prototype using Box2D – handling collisions

Read all posts about "" game

Welcome to the second part of the Box2D Hundreds prototype.

In this second part I am going to add some features which will make the prototype looking more like the original game, while having something different, just to make a new concept.

So the game now works this way:

* You can make a circle grow endlessly as long as you stay with the mouse over it
* The circle will stop growing, and will never grow again, if you leave the mouse from over it
* If a growing circle hits any other circle, both circles won’t be able to grow anymore and the size of the currently growing circle will be reduced by half.

Give it a try:

This is the commented source code for the main class:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class Main extends Sprite {
		// world definition
		private var world:b2World=new b2World(new b2Vec2(0,0),true);
		private var worldScale:Number=30;
		// custom contact listener
		private var customContact=new CustomContactListener();
		// speed of circles
		private var circleSpeed:Number=5;
		// body currently being touched
		private var currentBody:b2Body=null;
		// check if the mouse was over something
		private var overSomething:Boolean;
		public function Main() {
			// setting the custom contact listener
			world.SetContactListener(customContact);
			debugDraw();
			// adding 10 random circles
			for (var i:Number=1; i<=10; i++) {
				addCircle();
			}
			// adding boundary walls
			addWall(320,0,640,10);
			addWall(320,480,640,10);
			addWall(0,240,10,480);
			addWall(640,240,10,480);
			addEventListener(Event.ENTER_FRAME,update);
		}
		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 addCircle():void {
			var bodyDef:b2BodyDef= new b2BodyDef();
			bodyDef.type=b2Body.b2_dynamicBody;
			bodyDef.position.Set(Math.round(Math.random()*600+20)/worldScale,Math.round(Math.random()*440+20)/worldScale);
			bodyDef.userData={name:"sphere",canGrow:true,isGroving:false};
			var circleShape:b2CircleShape = new b2CircleShape(10/worldScale);
			var fixtureDef:b2FixtureDef = new b2FixtureDef();
			fixtureDef.density=1;
			fixtureDef.friction=0;
			fixtureDef.restitution=0.5;
			fixtureDef.shape=circleShape;
			var body:b2Body=world.CreateBody(bodyDef);
			body.CreateFixture(fixtureDef);
			// giving the circle a random direction
			var randomAngle:Number=Math.random()*2*Math.PI;
			body.SetLinearVelocity(new b2Vec2(circleSpeed*Math.cos(randomAngle),circleSpeed*Math.sin(randomAngle)));
		}
		private function addWall(pX:Number,pY:Number,w:Number,h:Number):void {
			var bodyDef:b2BodyDef=new b2BodyDef();
			bodyDef.position.Set(pX/worldScale,pY/worldScale);
			var polygonShape:b2PolygonShape=new b2PolygonShape();
			polygonShape.SetAsBox(w/2/worldScale,h/2/worldScale);
			var fixtureDef:b2FixtureDef=new b2FixtureDef();
			fixtureDef.shape=polygonShape;
			fixtureDef.density=1;
			fixtureDef.restitution=0.5;
			fixtureDef.friction=0;
			var theWall:b2Body=world.CreateBody(bodyDef);
			theWall.CreateFixture(fixtureDef);
		}
		// the core of the script, looking for the body touched and 
		// increasing the size of the circle shape
		private function queryCallback(fixture:b2Fixture):Boolean {
			var touchedBody:b2Body=fixture.GetBody();
			if (touchedBody.GetUserData()!=null) {
				overSomething=true;
				if (touchedBody!=currentBody) {
					if (currentBody!=null) {
						currentBody.GetUserData().isGroving=false;
						currentBody.GetUserData().canGrow=false;
					}
					currentBody=touchedBody;
				}
				if (touchedBody.GetUserData().canGrow) {
					touchedBody.GetUserData().isGrowing=true;
					var fixture:b2Fixture=touchedBody.GetFixtureList();
					var circleDef:b2CircleShape=fixture.GetShape() as b2CircleShape;
					var radius:Number=circleDef.GetRadius();
					circleDef.SetRadius(radius+1/worldScale);
				}
			}
			return false;
		}
		private function update(e:Event):void {
			world.Step(1/30,10,10);
			world.ClearForces();
			// checking for bodies under the mouse
			overSomething=false;
			world.QueryPoint(queryCallback,new b2Vec2(mouseX/worldScale,mouseY/worldScale));
			for (var b:b2Body=world.GetBodyList(); b; b=b.GetNext()) {
				if (b.GetUserData()!=null) {
					if (! overSomething&&b.GetUserData().isGrowing) {
						b.GetUserData().isGrowing=false;
						b.GetUserData().canGrow=false;
					}
					// keep moving circles at a constant speed
					var velocity:b2Vec2=b.GetLinearVelocity();
					var speed:Number=velocity.Length();
					var ratio:Number=circleSpeed/speed;
					velocity.Multiply(ratio);
					b.SetLinearVelocity(velocity);
				}
			}
			world.DrawDebugData();
		}
	}
}

and for the contact listener:

package {
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Dynamics.Joints.*;
	import Box2D.Dynamics.Contacts.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.b2Vec2;
	class CustomContactListener extends b2ContactListener {
		override public function PreSolve(contact:b2Contact, oldManifold:b2Manifold):void {
			// is the contact touching?
			if (contact.IsTouching()) {
				// getting the bodies involved
				var bodyA:b2Body=contact.GetFixtureA().GetBody();
				var bodyB:b2Body=contact.GetFixtureB().GetBody();
				// retrieving their user data objects
				var objA:Object=bodyA.GetUserData();
				var objB:Object=bodyB.GetUserData();
				var fixture:b2Fixture;
				var circleDef:b2CircleShape;
				var radius:Number;
				if (objA!=null && objB!=null) {
					if (objA.isGrowing) {
						objA.isGroving=false;
						objA.canGrow=false;
						fixture=bodyA.GetFixtureList();
						circleDef=fixture.GetShape() as b2CircleShape;
						radius=circleDef.GetRadius();
						circleDef.SetRadius(radius/2);
					}
					if (objB.isGrowing) {
						objB.isGroving=false;
						objB.canGrow=false;
						fixture=bodyB.GetFixtureList();
						circleDef=fixture.GetShape() as b2CircleShape;
						radius=circleDef.GetRadius();
						circleDef.SetRadius(radius/2);
					}
				}
			}
		}
	}
}

Download the source code. Next time, Nape version.

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