Circe Chain engine made with CreateJS – step 2

Read all posts about "" game

As promised, here is the second part of the Circle Chain engime made with CreateJS.

Following this fully commented script, you will learn how to handle mouse events and build the final, working engine:

// CreateJS features a Javascript library that lets you manage and co-ordinate
// the loading of assets, so we are going to use it
var preloader;
// manifest array will store every asset we need to preload, just like the
// manifest of a real world ship. As you can see, I am defining each manifest
// item with its relative path and an unique id
var manifest=[
	{src:"images/background.png", id:"background"},
	{src:"images/greencircle.png", id:"greenCircle"},
	{src:"images/redcircle.png", id:"redCircle"},
	{src:"images/redbullet.png", id:"redBullet"},
	{src:"images/greenbullet.png", id:"greenBullet"}
];
// the stage, the king of every game. 
var stage
// I need an array to store all my green circles, circleBitmap will do it
var circleBitmap = new Array();
// the red circle moved by the player
var playerCircle;
// the array which will store all bullets
var playerBullet = new Array();
// play function is the executed once the page loads
function play(){
	// first, I construct the stage as a Stage instance on the canvas id
	stage = new Stage(document.getElementById("canvas"));
	// this is how I am telling the stage to enable mouse interaction
	stage.mouseEventsEnabled = true;
	// then it's time to create the preloader
	preloader = new PreloadJS();
	// loadManifest is the method required to preaload all assets
	preloader.loadManifest(manifest);
	// and onComplete is the event trigger which will call loaded function
	preloader.onComplete = loaded;	
}
// loaded function will place all sprites on the stage and initialize the game
function loaded(event){
	// this is a variable I'll be using to assign a random direction to each
	// green circle
	var randomDirection;
	// look how I am picking up graphic assets from the preloader
	var bgImg=preloader.getResult("background").result;
	// once the background is picked up, I assign it to a Bitmap variable
     var bgBitmap = new Bitmap(bgImg);
     // then it's added to stage with addChild, just like AS3
	stage.addChild(bgBitmap);
	// the same concept is applied to the green circle, 10 times
     var circleImg=preloader.getResult("greenCircle").result;
     for(i=0;i<10;i++){
     	circleBitmap[i]=new Bitmap(circleImg);
     	// look at x and y properties
		circleBitmap[i].x=Math.random()*450+25-9;
		circleBitmap[i].y=Math.random()*450+25-9;
		// choosing a random direction
		randomDirection=Math.random()*2*Math.PI;
		// and defining xSpeed and ySpeed as custom properties
		circleBitmap[i].xSpeed=3*Math.cos(randomDirection);
		circleBitmap[i].ySpeed=3*Math.sin(randomDirection);
		// finally adding green circles to stage
		stage.addChild(circleBitmap[i]);
	}
	// same concept applied to the red circle
	var redCircleImg=preloader.getResult("redCircle").result;
     playerCircle = new Bitmap(redCircleImg);
	stage.addChild(playerCircle);
	// look how I am setting the game to be 30fps!! So easy!!
	Ticker.setFPS(30);
	// and this is something like AS3 enter frame event, calling gameLoop
	// function at every tick
	Ticker.addListener(gameLoop);
	// this is the mouse move listener, which will call moveRedCircle function
	stage.onMouseMove = moveRedCircle;
	// this is the mouse click listener, which will call fire function
	stage.onClick = fire;
}
// function to move the red circle according to mouse position
function moveRedCircle(e){
	// look at e event passed as argument
	playerCircle.x=e.stageX-9;
	playerCircle.y=e.stageY-9;	
}
// function to split the red circle when the player clicks the mouse
function fire(e){
	// look how I am removing listeners
	stage.onMouseMove = null;
	stage.onClick = null;
	stage.removeChild(playerCircle);
	// adding 4 red bullets
	var bulletDirection;
	var redBulletImg=preloader.getResult("redBullet").result;
	for(i=0;i<4;i++){
		playerBullet[i]=new Bitmap(redBulletImg);
		playerBullet[i].x=e.stageX-3;
		playerBullet[i].y=e.stageY-3;
		bulletDirection = Math.PI/2*i;
		playerBullet[i].xSpeed=6*Math.cos(bulletDirection);
		playerBullet[i].ySpeed=6*Math.sin(bulletDirection);
		stage.addChild(playerBullet[i]);
	}
}
function gameLoop(){
	// this loop just updates green circles position
	for(i=0;i500-9){
			circleBitmap[i].x-=500;
		}
		if(circleBitmap[i].x<0-9){
			circleBitmap[i].x+=500;
		}
		if(circleBitmap[i].y>500-9){
			circleBitmap[i].y-=500;
		}
		if(circleBitmap[i].y<0-9){
			circleBitmap[i].y+=500;
		}
	}   
	// checking for collisions and spreading new bullets. Nothing interesting,
	// just some math
	for(i=playerBullet.length-1;i>=0;i--){
		var removed=false;
		playerBullet[i].x+=playerBullet[i].xSpeed;
		playerBullet[i].y+=playerBullet[i].ySpeed;
		for(j=circleBitmap.length-1;j>=0;j--){
			var distX=(playerBullet[i].x+3)-(circleBitmap[j].x+9);
			var distY=(playerBullet[i].y+3)-(circleBitmap[j].y+9);
			if(distX*distX+distY*distY<144){
				var greenBulletImg=preloader.getResult("greenBullet").result;
				for(k=0;k<4;k++){
					playerBullet.push(new Bitmap(greenBulletImg));
					playerBullet[playerBullet.length-1].x=circleBitmap[j].x+9-3;
					playerBullet[playerBullet.length-1].y=circleBitmap[j].y+9-3;
					var bulletDirection = Math.PI/2*k;
					playerBullet[playerBullet.length-1].xSpeed=6*Math.cos(bulletDirection);
					playerBullet[playerBullet.length-1].ySpeed=6*Math.sin(bulletDirection);
					stage.addChild(playerBullet[playerBullet.length-1]);
				}
				stage.removeChild(playerBullet[i]);
				playerBullet.splice(i,1);
				stage.removeChild(circleBitmap[j]);
				circleBitmap.splice(j,1);
				removed=true;
				break;	
			}
		}
		if(!removed){
			if(playerBullet[i].x>500-3 || playerBullet[i].y>500-3 || playerBullet[i].x<-3 || playerBullet[i].y<-3){
				stage.removeChild(playerBullet[i]);
				playerBullet.splice(i,1);	
			}
		}
	}
	// at the end don't forget to update the stage to show what's going on
	stage.update();
}

and here is the result, now you can move the red circle on the stage with the mouse and start the chain reaction with the left mouse button:

Next time, the finished game.

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