Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

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
        box2d:false,
        showFPS:true,
        frameRate:60,
        tag:'gameCanvas', //the dom element to run cocos2d on
        engineDir:'../cocos2d/',
        appFiles:['MyFirstApp.js']
    };
    window.addEventListener('DOMContentLoaded', function () {
        //first load engine file if specified
        var s = d.createElement('script');
        s.src = c.engineDir + 'platform/jsloader.js';
        d.body.appendChild(s);
        s.c = c;
        s.id = '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({
    config:document.querySelector('#cocos2d-html5')['c'],
    ctor:function (scene) {
        this._super();
        this.startScene = scene;
        cc.COCOS2D_DEBUG = this.config['COCOS2D_DEBUG'];
        cc.setup(this.config['tag']);
        cc.Loader.shareLoader().onloading = function () {
            cc.LoaderScene.shareLoaderScene().draw();
        };
        cc.Loader.shareLoader().onload = function () {
            cc.AppController.shareAppController().didFinishLaunchingWithOptions();
        };
        cc.Loader.shareLoader().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(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({
    init:function()
    {
        this._super();

        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;
        helloLabel.schedule(function()
            {
                this.setRotation(rotationAmount++);
                if(rotationAmount > 360)
                    rotationAmount = 0;
                this.setScale(scale);
                scale+= 0.05;
                if(scale > 10)
                    scale =1;
            });

        layer1.addChild(helloLabel);
        this.addChild(layer1);

        
        return true;
    }

});

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

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 , ,

4. June 2012

 

 

This tutorial covers the process of getting Cocos2D-html setup and running.  If youCocos2dHTML5 already have completed this step, skip ahead.  It is also going to cover configuring a webserver, an optional ( but relatively easy ) step.  All right, lets get started.

 

First thing you need to do is get the cocos2d-html5 sources, which you can download here.

 

image

Locate the zip icon, as demonstrated in the picture to your left, click it.

 

Save the resulting download anywhere, just remember where you save it, we will need it in a few moments.

 

Now we are going to install a webserver.  This part is strictly optional, but if you want to take full advantage of the cocos demos, you are going to want a webserver installed.  It will also allow you to access your creation from different machines.  Besides, it’s a fairly simple process.  These instructions are for Windows only.

 

Now head over to WAMP and download their server.  The WAMP server is an all in one install of Apache, MySql, PHP and a few other applications, in many ways it is complete overkill, but like I said, it’s easy.  Pick whichever version is most appropriate, it doesn’t really matter which, so long as you choose the right one for your processor ( 32 or 64 bit ).

 

image

 

Now run the installer.  I choose the default value for every entry and let it install to C:\wamp.  If you saved to a different directory, adjust your path’s accordingly later on in this tutorial.  It is going to ask you to pick your default browser and default out to explorer.exe ( the shell, not to be confused with Internet Explorer the browser ).  You can explicitly choose a browser if you want but there is little reason to do so.  When prompted for mail settings, simply take the default.  WAMP server will now be installed and running in your system tray.

 

 

 

image

 

Like such.  Left clicking the tray icon will bring up the menu shown above.  Click localhost to see your webserver in action.

 

If everything went according to plan, you should see:

 

image

 

Now we want to extract the cocos2d-html archive we downloaded earlier.  Open up the zip and navigate the folders until you find a directory that looks like such:

 

image

 

CTRL+A select the entire contents of this folder in the zip and paste it  to C:\wamp\www\.

 

Now in your browser, you should be able to navigate to localhost/index.html and you will see:

 

image

 

If so, congrats, you have successfully set up Cocos2d for HTML5.  If not, make sure you have the proper contents in c:\wamp\www, and that it’s not buried in a subdirectory.  Now optionally you can open access to it up a bit so other computers on your network can see the website.  I am by no means an apache expert ( was born and raised on IIS ), so do not take this as authoritative in any way!

 

You want to edit httpd.conf, which you can do from the tray icon, like such:

image

 

 

Find and locate the following entries to match what I’ve done here ( with your IP address obviously ):

 

Set your IP and port to listen on, entry was originally Listen 80:

# # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # Listen 192.168.2.103:80

 

Set the server name to your servers name, or if you haven’t got DNS configured ( such as yourserver.yourname.com ) use your IP address like I have:

 

# # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # ServerName 192.168.2.103

 

Finally, grant access to your www folder:

 

<Directory "c:/wamp/www/"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride all # # Controls who can get stuff from this server. # # onlineoffline tag - don't remove Order Allow,Deny Allow from all </Directory>

 

You should now have full access to your webserver folder from other machines on your network ( and externally if you don’t have a firewall or have port forwarding configured ).  You can of course tweak the security settings until the cows come home.

 

Now, save your changes and restart your apache server, this can again be done from the tray icon, simply left click and choose Restart All Services.  If your icon doesn’t turn green, you have made an error in the httpd.conf file.

image

 

Again, the entire server portion is optional, you can just work from the local file system, but this allows you to make use of the full demo and test suite.

 

Speaking of which, if you now open your browser to http://yourserverIP/tests/index.html you should now have access to all the various cocos2d tests, like such:

 

image

 

Now you are set up and ready to go.  In the next tutorial, we will actually get to some coding.

 

Read tutorial 2

Programming , ,

3. June 2012

 

I mentioned Cocos2d-html a few days ago, a HTML5 port of the popular Cocos2D game library, they released a tech demo showing the game in action, Moon Warriors.

 

 



I'm not sure how well that will embed within my blog software, so if you have trouble playing you can open it directly here.  You can control it using the standard WASD keys, simply click the app to start ( or reload this page to stop ).  It was released under the GPL and you can download the full sources here.

 

 

As you can see, it’s a capable library and if you are interested in HTML5 game development, is certainly one to consider!

News ,

31. May 2012

 

 

Alright I admit it, something shiny and new came along and of course I am attracted to it!  As I mentioned a few days back, the Cocos2d-x team released Cocos2d-html, an HTML5 port of theCocos2dHTML5 popular Cocos2D iPhone game library.

 

I have never worked with a Cocos2D library yet, although Sony’s GameEngine2D is based heavily on it.  So I jumped in to the HTML5 version and I have to say I am extremely impressed so far.  Therefore I am going to do a (simple?) tutorial series on using Cocos2D-x to create HTML5 games.  I am not sure exactly how much detail I am going into but it should be kind of fun.  Expect a setup and Hello World tutorial post anytime.

 

Don’t worry though, I am still working on new PlayStation Suite tutorials, still intend to do an HTML5/RPG tutorial ( although whether I use HTML5, or a library like Cocos2D-x is up in the air, working with a library is so much nicer! ) in the near future and yes, I am going to finish my C++ game tutorial too.  What can I say, I love juggling projects.

 

So, if you are interested in developing 2D games targeting HTML5 web browsers be sure to keep an eye on this space, something will be coming soon!

 

If on the other hand, you are a Cocos2D veteran and you seem me doing something stupid, please let me know!

 

Smile

General ,

29. May 2012

 

This is one of those libraries I really have been meaning to check out.  Every time I turn around it seems like it’s been ported to another platform and today is no different!cocos2dbanner  Cocos2D can now target HTML5.

 

 

In the developers own words:

 

We are happy to announce that Cocos2d-html5 alpha is released!

This is the first version of Cocos2d-html5. Most of functionality and test cases from Cocos2d-X are implemented in Cocos2d-html5. Currently, Cocos2d-html5 utilizes canvas for rendering, the API is almost the same as Cocos2d-X and Cocos2d-iPhone. High level API will be wrapped in next phase, which will offer nicer interface for Javascript programmers and will also be compatible with the javascript binding of Cocos2d-x & Cocos2d-iPhone.

Cocos2d-html5 has two menu implementations. One is DOM menu, and the other one is canvas menu. DOM menu will run more efficiently, but the drawback is that all menu items will always above the canvas.

Test cases has being tested and works as expected on

  • Chrome 16 & 18,
  • Safari 5.1,
  • IE 9 & 10
  • Firefox 12.0.

 

You can run through all of the demos in the browser using the above link, or check out the getting started guide here.  At this point I think Cocos2D is basically available on every platform for every language short of BASIC for the Amstrad, but I am sure there is a port in the works!

 

I really have to check this library out one of these days.

News

Month List

Popular Comments