Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

8. June 2012


This tutorial is going to look at the basics of sprites and an area that initially confuses many people ( myself included! ), the positioning system used by Cocos2D.  I am going to build off the code we wrote in Tutorial 2, with a few minor changes.  First thing you need to do is make a copy of the MyFirstApp folder and paste it as the aptly named MySecondApp, so you end up with a folder looking like this:




Now we need to make a few changes. First, you can delete the file MyFirstApp.js within the MySecondApp directory as we are going to create a new one now.  Create another js file, MySecondApp.js.  We will worry about the contents in a few minutes.


First we need to make a couple small alterations to our existing code.  Open up Cocos2d.js and scroll to the very bottom.  We want to change:





Now open up main.js and change:


var myApp = new cocos2dApp(MyFirstAppScene);




var myApp = new cocos2dApp(MySecondAppScene);


That is all the changes we need to make to our boilerplate code.  In future tutorials, I will just assume you have already performed this step.


Finally before we get to coding, we need a sprite to work.  In your newly created folder, create a directory named images and save an image file there.  I am using this sprite, which has the file name Jet.png.  You of course can use whatever sprite you want.



Now lets fill in the code for MySecondApp.js


var MySecondApp = cc.Layer.extend(
        var layer1 = cc.LayerColor.create(
            new cc.Color4B(128, 128, 128, 255), 600, 600),
            jetSprite = cc.Sprite.create("./images/Jet.png");

        layer1.setPosition(new cc.Point(0.0,0.0));
        jetSprite.setPosition(new cc.Point(0.0,0.0));

        return true;

MySecondAppScene = cc.Scene.extend({
        var layer = new MySecondApp();


Much of this code should look virtually identical to MyFirstApp.js, as not much has changed.  Obviously our variable name has changed, but onEnter() is otherwise identical.


In our init() function, we are simply creating a background layer that is a solid gray color with the dimensions of 600x600 ( the same as our Canvas tag ).  We then create a cc.Sprite object using our Jet.png.  This is all that is involved in loading and creating a sprite object.  Now it's just a matter of adding the sprite to our layer, and adding our layer to MySecondApp’s layer. 


Lets load up our new app in the web browser and see what’s what!



As you can see, we have a 600x600 solid layer of gray and if you look closely in the bottom corner of our screen, you can see 1/4 of our jet sprite.  Depending on your background, this result might seem remarkably odd, as there are two factors at play here.


First, as I said in a previous tutorial, Cocos2D puts the origin at the bottom left hand corner, not the more traditional top left.  So if you have ever worked with textures or bitmap graphics before ( outside of OpenGL ), this is going to seem a little backwards to you.


Why would they do it this way?  I am guessing that  they followed the OpenGL way of doing things.  Now, why would OpenGL buck the trend and set the origin to the bottom left?  Well that involves a trip back to high school math and Cartesian coordinates.  If you think in those terms, suddenly starting from the bottom left makes a bit more sense.  Remember this graph:




In this particular case, if you are dealing with positive coordinates, you are in the upper right hand quadrant.  So if something is at say, position (2,2), it is above and to the right of the origin.


In the end it doesn’t really matter why, just be aware that the positions in Cocos2D start at the bottom left and you will be fine.


The next factor here is, where is the sprite’s anchor point.  Its all nice and good to say our jet is at (0,0)… but what part of our Jet is at (0,0)?  This is where the anchor point comes into effect.  The anchor point is where sprite translations ( rotating, translating, etc ) are performed relative to.  In Cocos2D, by default the pivot point is in the middle of the sprite, like illustrated by the red dot:



It is traditional to place the anchor point at the top left corner, but there are some real advantages to placing it at the center.  The least of which is rotation.  Consider the effects of rotating a sprite 1 degree per frame.


Here is the result with the pivot about the center:

(The code for the above animation is available here )



And here is the same image with the sprite anchor point moved to the top left:


(The code for the above animation is available here )



If you want to alter the anchor point, you can do it with this code:



The parameter to setAnchorPoint() is the new origin, in OpenGL coordinates.  0,0 == Bottom left, 0,1 == Top left, 1,0 == Top right, 1,1 == Bottom right.  Truth of the matter is, you should just adjust to the Cocos way of doing things unless you have a very good reason.


Alright… back to example, doing things the Cocos2D way.


Let say for example we wanted our sprite to be at the top right hand corner, we would accomplish this with the following code:

var size = cc.Director.sharedDirector().getWinSize(); jetSprite.setPosition(new cc.Point( size.width - jetSprite.getContentSizeInPixels().width/2, size.height - jetSprite.getContentSizeInPixels().height/2) );


Now here is the updated init() method with the Jet sprite centered to the screen.

        var layer1 = cc.LayerColor.create(
            new cc.Color4B(128, 128, 128, 255), 600, 600),
            jetSprite = cc.Sprite.create("./images/Jet.png");

        layer1.setPosition(new cc.Point(0.0,0.0));

        var size = cc.Director.getInstance().getWinSize();
        jetSprite.setPosition(new cc.Point(size.width/2,size.height/2));

        return true;


And finally, our end results:



Again, you can download the entire project here.



Read Tutorial 4

Programming , ,

7. June 2012


After spending so many years as a Windows/Visual Studio developer, Intellisense is a simple must have in my arsenal.  In fact, I believe my repeated use of Intellisense actually severedWebStormAndCocos2d the part of my brain that remembers functions and variables!


As I’ve been doing a lot of JavaScript development recently ( between Node.js and now Cocos2D ), I needed to recreate the Visual Studio experience.  I am an avid Notepad++ fan, but I never did get autocomplete working to my liking.  Then I discovered JetBrain’s WebStorm IDE and everything was right with the world.  If you want a full blown IDE for HTML and JavaScript development, you really can’t beat WebStorm ( it is however, not free software ).  Working with Node, auto-competition worked right out of the box.  With Cocos2D-html, there is a bit more work to do.


Here, we are going to cover that configuration process.  This process actually applies to configuring any JavaScript library to work with WebStorm, not just Cocos2D.


First things first, we need a project.  I am going to create one out of the code I created in the second Cocos2d tutorial. A WebStorm project is simply a directory full of code.  Let’s create one now.


Load up WebStorm ( I’m using 4.0.1 ).  Select File->New Project:



In the Create New Project dialog, under the location select the folder containing your project’s code, then in the Project name field enter your app directory name.  You may have to fight a bit with the UI to get it to work right, it really wants to create a new directory.  If you are creating a completely new project, you can ignore this bit.




Now it will prompt  you:




This is what we want, click yes.  This will simply create a .idea folder within your directory with the project data.  If all went well, you should now have a project like this:




Now the we have a working project, we can adjust the settings on it.  In the menu, select File->Settings:



Now scroll down and expand JavaScript and select Libraries:



On the right had side of the screen, locate and click the Add button:



Name it Cocos2D and click the Attach button:



Navigate to and select the Cocos2d folder, then click OK:



You may want to repeat the process for box2d and CocosDenshion ( audio library ) if you wish to use them as well.  Click OK when done.


Back in the settings menu, Click the Apply then OK button.



Now, when you are editing your JavaScript code, you will now have complete auto-completion data for the entire Cocos2D library:





Ahhhh, just like being back in Visual Studio with full Intellisense support. My brain can happily go back to forgetting all about functions and member variables! Smile



If you are looking for a solid JavaSript IDE, you really should check out WebStorm.  If you are looking for a great HTML5 based game library, you should check out Cocos2d-html. As you can see, they work well together.


The eagle-eyed viewer may have noticed the Sublime text project files. This is another great IDE (sorta) option that is worth checking out.  I switch back and forth between the two.

General , , ,

6. June 2012


As promised in the last tutorial, in this tutorial we are going to jump in and do some coding.  We are going to implement the obligatory Hello World example using Cocos2D HTML, with a twist ( literally ).  I warn you up front, this is going to look a great deal more complex than it actually is.  There is a certain amount of boilerplate code you need to get up and running, but it really isn’t all that difficult in the end.  In a future game, you will just do a series of copy and pastes and be off to the races.


The following goes into a lot of detail, more so than future tutorials.  There is however a TL;DR summary at the end, so if you prefer, simply read the code examples then jump ahead to the summary at the bottom of the post for an understanding of exactly what’s going on.


To make things a bit easier on yourself, create your game project in the same folder you extracted the Cocos2D-html archive to.  If you followed my directions exactly in tutorial 1, this directory will be c:\wamp\www.  Create a new folder for your project, I called mine MyFirstApp. 


Now that your directory is created, we are going to be creating a couple files.  First we need to create an HTML web page that is going to host our game.  Following convention ( and so Apache will serve it as the default ), I called mine index.html.  Enter the following code:


<html> <body style="padding:0; margin: 0; background: #fff;"> <div style="text-align: center; font-size: 0"> <canvas id="gameCanvas" width="600" height="600"> Your browser does not support the canvas tag </canvas> </div> </body> </html> <script src="cocos2d.js"></script>


This is pretty much stock HTML code.  The styling in the body tag is so our canvas tag will be flush with the left side of the screen, and because I wanted a white background.  Only two items here are really important.  First is the canvas tag, we need at least one canvas tag, as this is where Cocos2D draws everything.  Why 600 pixels?  That’s (edit- was) the content width of my blog.  So obviously, make your canvas whatever size you want it to be.  Finally we include our cocos2d.js script.


This segues nicely into the next task, go ahead and create another text file, this one called cocos2d.js.  Inside that file we type:


(function () {
    var d = document;
    var c = {
        COCOS2D_DEBUG:2, //0 to turn debug off, 1 for basic debug, and 2 for full debug
        tag:'gameCanvas', //the dom element to run cocos2d on
    window.addEventListener('DOMContentLoaded', function () {
        //first load engine file if specified
        var s = d.createElement('script');
        s.src = c.engineDir + 'platform/jsloader.js';
        s.c = c; = 'cocos2d-html5';


You may notice that this code block ends with ();  This is a self executing anonymous function.  Basically that means after it is finished being defined, it will immediately be called.


So what exactly are we doing here?  First we care creating a configuration variable called c.  This file consists of a number of configuration settings for initializing the Cocos2D engine.  Lets take a quick look at each value:


COCOS2D_Debug: This controls the debug level Cocos2D engine. In release set to 0

box2d: Tells Cocos2D if it needs to initialize the box2d physics engine

showFPS: Enable/disable a frames per second counter being displayed each frame

tag: This is the HTML element that cocos2D will render to.  In our case, our canvas tag

engineDir: This is the directory the cocos2D libraries are installed in.  In our case, up one directory from cocos2d.js in the folder cocos2d

appFiles: This is an array containing all of the your script files.  If you add a js file to your project, add it to this array.  This causes it to be loaded by the loader.


Next we register an event handler that will be fired once the DOM has been loaded ( meaning the page is done loading and JavaScript is setup and ready ).  We then create a <SCRIPT> tag in our HTML page with the id ‘cocos2d-html5’ and add a reference to jsloader.js script as well as our configuration variable c.


At this point, the jsloader.js script now loads all of the various libraries required by cocos2d into the HTML file.  Once it is done loading all of the library files, it calls a user defined script named main.js. You need to create this file in the root of your project.


Now let’s go ahead and create main.js:


var cocos2dApp = cc.Application.extend({
    ctor:function (scene) {
        this.startScene = scene;
        cc.COCOS2D_DEBUG = this.config['COCOS2D_DEBUG'];
        cc.Loader.shareLoader().onloading = function () {
        cc.Loader.shareLoader().onload = function () {
    applicationDidFinishLaunching:function () {
        var director = cc.Director.getInstance();
        director.setAnimationInterval(1.0 / this.config['frameRate']);
        director.runWithScene(new this.startScene());

        return true;
var myApp = new cocos2dApp(MyFirstAppScene);


We are creating a new object by extending cc.Application.  If you are familiar with C++, Java or C# you may be looking at this code and thinking it is both vaguely familiar and different at the same time.  There is a good reason for that.  JavaScript isn’t really “object oriented” in the way you are familiar with, it is prototype based.  This is beyond the scope of what I can explain here, but basically there are no classes.  Instead there are “prototypes” that you clone and extend.  So essentially you define something once, which is then used as a prototype for creating “objects” in the future.  Clear as mud?


Essentially what we are doing here is defining our cocos2DApp object to extend the cc.Application prototype.  This is a pretty common behavior in working with Cocos2D, so hopefully you can wrap your head around it.  We then implement the ctor ( constructor ) and applicationDidFinishingLaunching.  Again, if you are used to C++ like languages, you can think of cocos2DApp as being derived from cc.Application, then overriding the default constructor and a virtual method.  If you aren’t a C++/C# or Java programmer, forget everything I just said. Smile


First, up is the ctor, which simply results in the creation of the prototype cc.Application which cocos2DApp extends.  super() can be a confusing concept to understand, for more details read this. ( warning, NSFW language ).  One thing to keep in mind, in JavaScript, the constructor ( or ctor ) is just another function, unlike in other languages. 


We pass the type of Scene we want to start our app with, we will be creating this in a moment.  This is value the parameter scene holds.  We then call _super() as described earlier.  Next we setup cocos using the values we set in the value c earlier in cocos2d.js.  Next we invoke the global Loader object via cc.Loader.shareLoader().  onloading is a call back that will be called when the loader is executing, which effectively renders the loading screen.  preLoad is an important function for loading user data files, which we will user in a later tutorial.


In applicationDidFinishLaunching ( which is predictably called when the application finishes launching! ), we initialize the Director object. Director is a global object that basically controls the execution of everything, we will be seeing a lot of it later on.  For now just realize that Director is very important.  Why will become clear in time.  The .getInstance() call is where the singleton part of the equation comes in.  It’s well beyond the scope of what I can go into, but for now just think about it as a globally unique shared variable.


The heart of our cocos2dApp though is the applicationDidFinishLaunching function.  This is a function that will be called once your cocos2dApp class is loaded, cocos2d is setup and it is what gets the party started.  First we tell the ( all important! ) Director if we want to display the frames per second counter on screen and that we want to update using the framerate specified in c configuration in cocos2d.js.  Next we tell Director to start running using the scene type we passed in to the constructor.  The director only ever has one scene at a time active, and as I said earlier, Cocos2D organizes your game Scene by scene.  This is the point where your (only) Scene is created and execution is started. 


Finally we create an instance of cocos2dApp named myApp and pass it the scene MyFirstAppScene.


Now lets create that scene object, create a file named MyFirstApp.js as such:

var MyFirstApp = cc.Layer.extend({

        var s = cc.Director.getInstance().getWinSize();

        var layer1 = cc.LayerColor.create(new cc.Color4B(255, 255, 0, 255), 600, 600);
        layer1.setAnchorPoint(new cc.Point(0.5,0.5));

        var helloLabel = cc.LabelTTF.create("Hello world", "Arial", 30);
        helloLabel.setPosition(new cc.Point(s.width/2,s.height/2));
        helloLabel.setColor(new cc.Color3B(255,0,0));
        var rotationAmount = 0;
        var scale = 1;
                if(rotationAmount > 360)
                    rotationAmount = 0;
                scale+= 0.05;
                if(scale > 10)
                    scale =1;


        return true;


var MyFirstAppScene = cc.Scene.extend({
        var layer = new MyFirstApp();

Just like we did when creating our cocos2dApp, we are creating MyFirstApp by extending a Cocos2D prototype, in this case ccLayer.  If you have ever worked in a graphic application like Photoshop or GIMP, the concept of a layer should already be familiar to you.  If the term is new to you, think of a layer as an image or graphic, that might be transparent in parts.  You can layer ( thus the name ) layers over top of each other to create a compound image.  This image illustrates the concept as well as any I could find:




You can think of MyFirstApp as representing the entire collection of layers, which in the end will ultimately be drawn to our HTML canvas tag.


As I said, our canvas can be made out of a collection of layers, and the first thing we want to do is create a solid yellow layer.  That is what this call does:

var layer1 = cc.LayerColor.create(new cc.Color4B(255, 255, 0, 255), 600, 600);

We are creating a layer 600x600 in size ( the same as our canvas tag ), filled with the RGBA color 255,255,0,255.  These numbers represent the red, green, blue and alpha values respectively, as represented by a value from 0-255.  The alpha value can be thought of as the amount of transparency in the layer, in this case 100% opaque.  As you can see, we created our color with a call to cc.Color4B, you will see this naming convention quite often. 


Now that we have a solid yellow layer, we need to position it.  Positioning in Cocos2D might be a bit different from what you are used to.  Instead of positioning elements from the their top left, they are positioned by their center point by default.  Additionally Cocos2D coordinates start at the bottom left of the screen instead of the top left.  Therefore when we set the position of our layer, we want it to be the center of the screen.


Now we want to create our HelloWorld text, which we do by creating a cc.LabelTTF ( TTF = True Text Font ), with our string “Hello world” using the font family Arial and font size of 30.  We too want the Hello World label centered to the screen and we want it to be red in color.  We then declare two local variables rotationAmount and scale, which we will use in a second.


The next line is key, we are declaring a lambda ( or anonymous ) function that we pass as a parameter to the schedule function.  End end result is, the following code will be executed every update ( which we set to 60 times per second earlier ) as long as our scene is active.  Essentially what happens is Director calls our Scene ( MyFirstApp ) to update 60 times per second, and our Scene in turn calls the update function of each node that registered to be updated.  This line is registering the function that is going to be called during updating.  ( This is greatly simplifying the actual process, but will do for now ).  Essentially, all this function does is rotate the text and scale it until it is 10 times in size, at which point it starts over.


Finally, we add our Hello World label to our layer, and add our layer to our MyFirstApp variable.


Now we create our scene, MyFirstAppScene.  This is the value we passed in to the constructor cocos2dApp earlier.  MyFirstAppScene extends cc.Scene and overrides the OnEnter method, which is called when the scene is activated ( in the RunWithScene call ).  In this case, we simply call up to cc.Scene with a call to this._super(), then create an instance of our layer MyFirstApp and add it to our scene.  This causes our layer to be created and displayed.


Here are the end results of all our activity:



TL;DR overview of what just happened:


  1. index.html is loaded in the web browser
  2. Our canvas tag is defined
  3. cocos2d.js then loaded ( within index.html )
  4. cocos2.js creates a SCRIPT tag in our index.html, injects configuration settings as well as a reference to jsloader.js
  5. jsloader loads all of the required cocos2D libraries, then invokes main.js
  6. main.js loads cocos2D, preloads assets, initializes the director then runs our scene
  7. our scene MyFirstAppScene creates a new layer MyFirstApp


Your game is now running.  We will take a closer look at program execution and handling input shortly.


You can download the whole project here.  Simply extract it to your www folder and open index.html in your browser.



Read Tutorial 3

Programming , ,

6. June 2012


I can always tell when Diablo 3 servers are being patched as I get an influx of visitors viewing this page.  I wrote that when I was experiencing crashes when they last patched the Diablo 3D3Boom servers.  It would appear the server patch crashes are still occurring.


To people having this problem, this post is a much more concise description of the problems I had, and the fix.  So if you are unable to log in to Diablo after a server patch, or the patcher is giving you “Diablo III is already running” or “Diablo III has stopped working”, this might be the fix to your problem.


Basically what it boiled down to is the Blizzard installer gave me the en-GB ( Great Britain ) installer instead of the en-US one.  This is all fine and good, until Blizzard releases a patch.  The problem is, the US patch is released first, causing all the people connecting to the US servers with a non-US client to crash until the other servers are patched.


It may be possible to work around the problem by manually editing the patch_url in your agent.db file, I had some initial success this way.


However, the *best* solution, is to reinstall using the client native the server you are playing on.  Granted, this is a giant pain in the backside, especially if your internet connection has usage caps!


That said, the actual BEST solution, is for Blizzard to fix this problem, or failing that, roll out all the patches at once!


Hopefully this helped a few of you get over the Diablo 3 patching woes!  If nothing else, it allowed me to create that Diablo mushroom cloud graphic. Smile



EDIT: For those that don’t want to re-install, you can try editing the patch_url manually.  Worst case scenario… you will have to re-install! Smile


To do so, follow these instructions.  Of course, these instructions are for switching to the Asian server, so substitute en-US for American, and en-GB for European servers.  Also, be sure to note that there are multiple copies of the file you need to edit, not just one!

Totally Off Topic

5. June 2012


As part of the same document that announced the PlayStation Mobile compatible phones fromplaystation-mobile-on-htc HTC, Sony also released a list of developers currently working on PlayStation Mobile content.  Give it a look and I believe that you will agree that it is fairly impressive:





List of Third Party Game Developers and Publishers



ASGARD Co.,Ltd. 
CYBERFRONT Corporation
eitarosoft, inc.
FromSoftware, Inc
GungHo Online Entertainment, Inc.  
HAMSTER Corporation




Atomicom Ltd.
Beatnik Games Ltd. 
Big Head Games Ltd.
Crash Lab Ltd.
Futurlab Ltd. 
Green Hill
Honeyslug Ltd.
Icon Games Entertainment Ltd. 
Omni Systems Ltd.
Origin8 Technologies Ltd.
Playerthree Ltd. 
Index Corporation 
Kadokawa Games, Ltd.
Kadokawa Shoten Publishing Co., Ltd. 
MarvelousAQL Inc.
NCM Entertainment Corporation / Forever Entertainment S.A. Group
Nippon Ichi Software, Inc.
Pygmy Studio.Co., Ltd.
Q Entertainment Inc.
SEGA Corporation
SUCCESS Corporation
34  companies in total
22 companies in total
Pompom Software Ltd.
Quirkat Inc.
Retroburn Game Studios Ltd.
Ripstone Ltd. 
SFB Games Ltd.
Spinning Head Software Ltd. 
Thumbs Up
Tikipod Ltd.
Triangle Factory
Wired Productions Ltd.




Some pretty impressive names in there, from Sony, From Software and GameLoft to Nippon, Tecmo and Sega.  If you want, you can download the original PDF here.  The press release is available here.  With heavy weight support behind their effort, Sony may become a big player in the ( currently horrible? ) Android game market.



So, if Sony had this many developers lined up and working on PlayStation Mobile games, why didn’t they mention that at the E3 press conference???  I am sure nobody would have minded a few minutes axed out of the Wonderbook demonstration!


Month List

Popular Comments