Cocos2D for the Web

Breakout Clone Tutorial : Part 1

NOTE: This tutorial is for v0.1
Full v0.2 source code available on github

Introduction

This series of tutorials will guide you through creating a new project and writing a very simple breakout clone. You can try out the final result on the demo page. If you have any questions or comments please at them to the comments section at the end of this tutorial.

For part 1 we won’t be writing any code but we will create the initial project and go through how to write use modules and classes.

Installation

Windows

Download and launch the installer available in the downloads section.

Linux or Mac OS X using npm

If you have Node.js and npm installed you can install Cocos2D JavaScript as a package.

npm install cocos2d

Linux or Mac OS X using the ZIP archive

If you don’t have, or don’t want to use npm, you can install by downloading the latest ZIP from the downloads section.

Then from your terminal run sudo ./install.sh. The script will copy Cocos2D JavaScript to a global location of your choice and symlink the executable to /usr/local/bin/cocos

Creating a New Project

On Windows you should use the ‘Create project’ shortcut from your startmenu and point that at a new folder named breakout. The name of the folder will be the name of your project.

On Linux and Mac you create a new project from the command line using the cocos command.

cocos new ~/Projects/breakout

Now lets make sure that’s working correctly by launching the development Web server.

On Windows simply double click the “Server project” shortcut inside your project’s folder.

On Linux and Mac open your terminal and run:

cd ~/Projects/breakout
cocos server

Open your web browser at http://localhost:4000. If everything works you will see a black rectangle with “Breakout” in large text.

Modules

If you’ve only written JavaScript for websites then the concept of JavaScript modules may be unfamiliar to you. Cocos2D JavaScript implements the CommonJS Modules Spec. What this means is that when you wish to access objects from another file (a module) you first have to import them.

Importing a module is done using the global function require. You will almost always want to import the cocos2d module which would be done by adding a require call to the very top of the file like this.

var cocos = require('cocos2d');

This is assigning all the objects exported from the cocos2d module into the cocos variable. By using this variable you have access to any object or function the module decided to export. This also works in your browser’s JavaScript console. Give it a try on the breakout project. Open it in Chrome and then open the JavaScript Console. In there simply enter require('cocos2d'); and inspect the returned object. You will see something like the image below.

Classes

Most classes in Cocos2D JavaScript extend from a base object called BObject. This adds a lot of extra functionality that isn’t normally available to a JavaScript prototype (class). In order to extend from BObject (or a subclass of it) you will use the extend class method and pass in an object literal containing the new methods and properties. Here’s an example.

var Cat = BObject.extend({
    voice: "meow",
 
    init: function() {
        Cat.superclass.init.call(this);
    },
 
    speak: function() {
        alert(this.get('voice'));
    }
});

This creates a new class called Cat which has a property called voice and a method called speak. The init method is the constructor which you will used for any initialisation your object needs.

To create an instance of a class you call the create class method. Anything arguments given to create is sent to the init method. So, to create an instance of the above class and call a method on it we would do:

var myCat = Cat.create();
myCat.speak();

Properties

Properties on subclasses of BObject have some special abilities such as bindings and getters/setters. To support this, rather than using the usual JavaScript dot-notation to access a property you should instead use the get and set methods.

To access the voice property from our Cat class we do:

myCat.get('voice');

And to change the property we do:

myCat.set('voice', 'ROAR!');

Resources

We wouldn’t be able to do much without resources such as images, tilemaps and audio files. To include these in your application place them inside the src/resources/ folder. Any files you put inside the src/resources/ folder will automatically be compiled into the resulting JavaScript file. Avoid putting unused files in here if you want to keep the filesize to a minimum.

To acces your resources in code you will use the resource global function. This will return an object or string containing the resource data. Most of the time you will just be passing the path to one of the Cocos2D JavaScript objects and letting that deal with the resources.

If you had an image named src/resources/sprites.png you would access it like this.

resource('/resources/sprites.png');

This will return a HTML image element.

Application Entry Point

The entry point for our application is the src/main.js file. Any code you put inside a function named exports.main inside main.js will be executed automatically when the web page loads. You don’t need to listen for any load events yourself, it’s all handled for you.

Posted

Comments

Nader Rahimizad

ago, Nader Rahimizad said

Hi Can you upload the source code for this Breakout project for us to try and use it as a new game template?

Ryan

ago, Ryan said

I wasn’t going to release it until I finished the tutorial, but here’s the final code that’s used for the demo.

https://github.com/ryanwilliams/cocos2d-breakout

Checkout the code and run

git submodule update --init

Then start the server with

./cocos server

Paul

ago, Paul said

A couple of things I am not understanding about the framework, possibly related:

You mention @super as a compiler recognized function or macro – but JS is interpreted generally – so what is going on with that.

The tutorial ask us to run a server from the downloaded framework. Anything special going on there ? Can we not just open local html file in a browser, and run it ?

I am very interested in this development, as its a friendly language for games development, and can deploy widely. Browsing around the site however, have not found a high level overview of the framework that answers these questions. Much detail on the API though, and its early days. Perhaps some high level overview, background etc would be a valuable introduction

Ryan

ago, Ryan said

@Paul

The compiler is really just a script that merges all the separate JS files into one big file. While doing this it expands the @super keyword. The compiler also embeds all your images and tilemap files into the same final .js file. This means the result is a single .js file that you need to add to your site. No need to worry about paths to images or any of that stuff.

All the server does is run the compile script for every request, it’s so you don’t have to run ./cocos make every time you want to test a change.

I’ll be adding more info soon, cocos2d-javascript is still in the early stages, but I hope to have a proper 0.1 release soon. With that release I’ll get some guides up to explain the basic concepts in more detail.

sonre

ago, sonre said

Python scripts should be updated. They won’t work with Python 3.x
Reason: print statement is replaced with print() function in 3.×.

Alberto Rodríguez

ago, Alberto Rodríguez said

Hello Ryan,

I’ve followed the steps of the tutorial and everything goes well until the point where I go to the Chrome console and type:

require(‘cocos2d’);

I am getting this error:

ReferenceError: require is not defined

I ignored this and continued with part 2 of the tutorial but I can’t get the Bat to show on the screen. I just get the same empty box from the beginning.

Then I went to download the source for the example from the git repository, without using Git, I just downloaded the source as a Zip file, but when I type on the console:

cocos server

I am getting:

“Unknown command : server”

What am I doing wrong?

Thanks

Ryan

ago, Ryan said

Hi Alberto,

Sounds like it’s not picking up the cocos2d code. In your project do you have a cocos2d folder containing the entire cocos2d-javascript code? That should have been copied into your project when you ran cocos new. If you’re not using git you have to pass the -g flag when calling it, like:

cocos new C:\Breakout -g

And the resulting folder should contain a cocos2d folder something like:

cocos
cocos.bat
cocos2d/
make.js
public/
src/

If it is missing let me know the steps you did, maybe it’s a bug. But you can fix it by simply copying the cocos2d-javascript project into that folder.

Alberto Rodríguez

ago, Alberto Rodríguez said

I’ve done what you said but I’m still getting "ReferenceError: require is not defined ".

The steps that I made to get this issue are:

1. Downloaded “ryanwilliams-cocos2d-javascript-b493e33” from https://github.com/ryanwilliams/cocos2d-javascript/zipball/master and unziped it in “C:\cocos2d-javascript”

2. Executed the following in the command prompt:

cd C:\cocos2d-javascript

C:\cocos2d-javascript>cocos new C:\Breakout -g
Creating cocos2d-javascript project in: C:\Breakout
Creating new directory : C:\Breakout\src
Creating new directory : C:\Breakout\src/resources
Creating new directory : C:\Breakout\public
Copying cocos2d

C:\cocos2d-javascript>cd c:\Breakout

c:\Breakout>cocos server
Listening at http://localhost:4000/

3. Opened my browser at http://localhost:4000/

I got a page with the text Breakout and an empty box.

4. Typed the following in the Chrome console:

require(‘cocos2d’);

  • ReferenceError: require is not defined *

Ryan

ago, Ryan said

The problem is a bug when running on windows. It doesn’t like backslashes in the paths. I’ve just pushed a fix so if you redownload cocos2d-javascript (commit is 487740b) it should work properly now.

Sorry about that.

shebeena

ago, shebeena said

1.When I installed the installer for windows ,i couldnt see the resource file in src.
2. when i clicked on the serve project ,command prompt just comes and dis appears.
3. whenever i clicked on the link that is http://localhost:4000 always shows a message “unable to connect”
why is it so?

Ryan

ago, Ryan said

Hi Shebeena,

Which version of Windows are you running? Does the project it generated for you have a file name src/main.js? If so then we can assume that part has worked fine.

Could you try this and tell me what the error you see is:

  1. Open command prompt (start → cmd)
  2. cd “path to your project”
  3. “c:\Program Files (x86)\Cocos2D JavaScript\bin\cocos.bat” server

Thanks

Ryan

ago, Ryan said

There was an issue with the Windows installer version. I’ve uploaded a fix. Please download it again, uninstall the old version and install the new version. You won’t need to recreate your project.

shebeena

ago, shebeena said

@Ryan ,I just uninstalled the old version and installed new version as you mentioned.Now its working.Thanks ryan

Corgalore

ago, Corgalore said

I noticed when creating a new Project under Windows if you create a folder with spaces in the name that the main.js file created will contain invalid javascript because it replaces the space with a dash. Just a heads up. Easy fix from my end.

Patrick

ago, Patrick said

I absolutely love this engine. My only problem (as a javascript beginner) is the language used in your tutorials. Class, subclass, nodes.. etc. There is no such thing as classes in javavscript, there are objects and child objects, and the use of the phrase ‘nodes’ should be replaced with layers in my opinion, in order to fall in line with cocos2d in general.
I believe when you refer to javascript objects as classes it simply confuses the javascript beginner, unnecessarily since javascript isn’t an OOP language.
Nonetheless, I love this engine, I can see it easily becoming the defacto gaming engine for javascript. Keep it going, PLEASE!

Dani

ago, Dani said

Hello all,

I think I found an issue on windows. Created a new project called game-dev. After building and compiling the project I get an js error “Unexpected toke -”. Problem is in the js file Game-dev should be Game_dev.
This fixed my problem.

Cheers,
Dani

Jesselee

ago, Jesselee said

After installing node.js and npm I run npm install cocos2d.
Output:
cocos2d@0.1.0 ./node_modules/cocos2d

then I run: cocos new ~/Projects/breakout
and I get: -bash: cocos: command not found

What am I doing wrong?

Ryan

ago, Ryan said

Hi Jesselee,

NPM has changed a little since this was written, I need to update. What you need to do is add the -g flag to make it a global install:

npm install -g cocos2d

Also, I’ve just pushed v0.1.1 which fixes an issue with newer versions of Node. You should get that automatically if you install now.

Mikael

ago, Mikael said

I have installed it using the ZIP archive, but when I use any cocos command, I get “No such file or directory”.
What is the problem?

takeyama

ago, takeyama said

I install success.
My server has a firewall.
You can not use 4000 port.
Is there any way to change the port ???

Ami Heines

ago, Ami Heines said

@takeyama, try running:
cocos server —port 80
or any other port your firewall allows.

zhengyu

ago, zhengyu said

Hey, Can you recommend the use of certain tools? So when I write cocos2d Code ,It can have some tips, or when I make a mistake, can tell me where did I go wrong ?

Todd Rimes

ago, Todd Rimes said

Is there a MAXIMUM version of node.js I should use? Or should I just hack the cocos2d code (which I hate to do)?

I’m getting this:
toddsmac:cocos2d todd$ cocos
The “sys” module is now called “util”. It should have a similar interface.

node.js:201
throw e; // process.nextTick error, or ‘error’ event on first tick
^
Error: require.paths is removed. Use node_modules folders, or the NODE_PATH environment variable instead.
at Function.<anonymous> (module.js:376:11)
at Object.<anonymous> (/usr/local/lib/node_modules/cocos2d/bin/cocos.js:7:8)
at Module.compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter.
tickCallback (node.js:192:40)

Todd Rimes

ago, Todd Rimes said

duh – found the answer here: http://cocos2d-central.com/topic/472-cocos-command-issue/

Cristian Salamea

ago, Cristian Salamea said

Hello there is fixes for v0.6.6 node ?

Regards,

Add Comment

If you want to add a comment, then simply fill in the form below. All fields are required.