From zero to a complete game with Cocos2d HTML5 – Step 1

Read all posts about "" game

Time to learn something about Cocos2d HTML5, the HTML5 version of the famous Cocos2d-x project.

In this tutorial series I am going to cover the creation of Circle Chain game, which I already developed in AS2, AS3 and Stencyl for iOS.

I assume you have no idea even how to install Cocos2D HTML5 so I am starting from scratch. Before we even start installing Cocos2D HTML5, if you want to test your work offline you need to turn your computer into a webserver because most browsers deny access to certain functions such as XMLHttpRequest that fails for “file:// ” protocol, while Cocos2d HTML5 engine depends on this to read many files.

I found WampServer for Windows the best solution for my needs, if you have a Mac you can try MAMP. Follow instructions in the sites about installing the webserver and where to deploy folders which need to be reached through localhost.

If you don’t want to install such softwares on your computer, you can test your work uploading it to a web space you own.

Then download Cocos2d-HTML5 and place the content of the archive into the folder your webserver will reach as localhost.

Now it’s time to write our first snippet of code. Create another folder into the localhost directory (C:/wamp/www if you are using WampServer), and inside such folder create a file called index.html, with this content:

<!DOCTYPE HTML>
<html>
	<head>
		<title>Circle Chain Cocos2d HTML5 version</title>
		<script src="cocos2d.js"></script>
	</head>
	<body style="padding:0px;margin:0px;background-color:white">
		<canvas id="gameCanvas" width="500" height="500"></canvas>
	</body>
</html>

It’s just the basic page including a canvas element in it. Just have a look at line 5 where I load cocos2d.js and line 8 where I assign gameCanvas id to the canvas.

cocos2d.js file will contain a template file about the configuration of the project:

(function () {
	var d = document;
	var c = {
		menuType:"canvas",
        	COCOS2D_DEBUG:2, // full debug mode
		box2d:false, // no physics in this game
		chipmunk: false, // no chipmunk engine
		showFPS:true, // let's show the FPS meter
		frameRate:60, // 60 frames per second
		tag:"gameCanvas", // id of the canvas element
		engineDir:"../cocos2d/", // path to your cocos2d installation
		appFiles:["circlechain.js"] // path to the main game file
	};
	window.addEventListener('DOMContentLoaded', function () {
		var s = d.createElement("script");
		s.src = c.engineDir + "platform/jsloader.js";
		d.body.appendChild(s);
		s.c = c;
		s.id = "cocos2d-html5";
		document.ccConfig = c;
	});
})();

In most cases you will be able to use this same file just changing line 12, where you specify the path to the main game file and maybe line 9 if you called the canvas id with a different name.

Another file you will need in the same path is main.js:

var cocos2dApp = cc.Application.extend({
	config:document.ccConfig,
	ctor:function (scene) {
		this._super();
		this.startScene = scene;
		cc.COCOS2D_DEBUG = this.config["COCOS2D_DEBUG"];
        	cc.initDebugSetting();
		cc.setup(this.config["tag"]);
		cc.Loader.getInstance().onloading = function () {
			cc.LoaderScene.shareLoaderScene().draw();
		};
		cc.Loader.getInstance().onload = function () {
			cc.AppController.shareAppController().didFinishLaunchingWithOptions();
		};
		cc.Loader.getInstance().preload([
		]);
	},
	applicationDidFinishLaunching:function () {
		var director = cc.Director.getInstance();
		director.setDisplayStats(this.config["showFPS"]);
		director.setAnimationInterval(1.0 / this.config["frameRate"]);
		director.runWithScene(new this.startScene());
		return true;
	}
});     
var myApp = new cocos2dApp(circlechain);

Just like before, in most cases you will be able to completely reuse it, with the exception of the last line where you’ll want to change the argument of cocos2dApp function.

Finally circlechain.js is simpler than you can imagine if you come from Actionscript, there are sprites and events and layers, have a look:

var circlechain = cc.Scene.extend({
	onEnter:function(){
		this._super();
		var layer = new circleChainGame();
		layer.init();
		this.addChild(layer);
	}
})

var circleChainGame = cc.Layer.extend({
	init:function(){
		this._super();
		var circleSpeed = 2;
		var s = cc.Director.getInstance().getWinSize();
		var gameLayer = cc.LayerColor.create(new cc.Color4B(0, 0, 0, 255), 500, 500)
		for(i=0;i<10;i++){
			var greenCircle = cc.Sprite.create("greencircle.png");
			var randomDir = Math.random()*2*Math.PI;
			greenCircle.xSpeed=circleSpeed*Math.cos(randomDir);
			greenCircle.ySpeed=circleSpeed*Math.sin(randomDir);
			gameLayer.addChild(greenCircle);
			greenCircle.setPosition(new cc.Point(Math.random()*500,Math.random()*500));
			greenCircle.schedule(function(){
     			this.setPosition(new cc.Point(this.getPosition().x+this.xSpeed,this.getPosition().y+this.ySpeed));
     			if(this.getPosition().x>500){
					this.setPosition(new cc.Point(this.getPosition().x-500,this.getPosition().y));
				}
				if(this.getPosition().x<0){
					this.setPosition(new cc.Point(this.getPosition().x+500,this.getPosition().y));
				}
				if(this.getPosition().y>500){
					this.setPosition(new cc.Point(this.getPosition().x ,this.getPosition().y-500));
				}
				if(this.getPosition().y<0){
					this.setPosition(new cc.Point(this.getPosition().x ,this.getPosition().y+500));
				}
			})
		}
     	this.addChild(gameLayer);
		return true;
	}
});

You can think about schedule method as an enter frame listener, and a layer as a display object container.

And here is the result of the first step, with our ten green circles moving around the screen:

You can also download the source code. Next time, I’ll show you how to add interactivity.

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