Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
13. July 2012

 

This is the first part of my adventure creating a simple game for my daughter

 

One of the catches with a JavaScript game, as you saw from this earlier tutorial, to take full advantage you need a client and a server.  However, once you want the server to start doing “stuff”, you want as much control over it as possible.  The advice “write your own!” is normally remarkably stupid, but with Node, it actually isn’t!  In fact, you can create a fully functioning server in only a couple lines of code.  If you are looking for a way to deploy an advanced JavaScript application, read on.

 

If you’ve never experienced Node before, basically it is a server side implementation of Google’s V8 Javascript engine, and a whole TON of plugins to do just about everything.  Perhaps the biggest selling point is, it allows you to work in both Javascript on the client and server.  It is also easy to deploy, massively asynchronous, scalable and frankly, kinda cool.  The first thing you are going to need to do is install it on your computer.  The install process is remarkably simple, although when you are done I would suggest adding node to your PATH environment variable if you are working on Windows.

 

Now that you have Node installed, let’s create a simple server.  Create a file called server.js like this:

 

var express = require('express'), server = express.createServer(); server.use('/cocos2d', express.static(__dirname + '/cocos2d') ); server.use('/cocosDenshion', express.static(__dirname + '/cocosDenshion') ); server.use('/classes', express.static(__dirname + '/classes') ); server.use('/resources', express.static(__dirname + '/resources') ); server.get('/', function(req,res){ res.sendfile('index.html'); console.log('Sent index.html'); }); server.get('/api/hello', function(req,res){ res.send('Hello Cruel World'); }); server.listen(process.env.PORT || 3000);

 

And… that’s it, a fully functioning web server.

 

That first line is the key, where we require(‘express’).  Express is the module that is doing the heavy lifting on the server side.

 

There is however a small amount of configuration you need to do.  You need to tell node to install the express module.  This is pretty simply done though, open a command prompt and navigate to your project directory, then type:

npm install express

 

npm is the node package manager, and it will download and configure your project to work with express.  Now that we are configured, lets get back to code.

 

The next four lines are defining a series of static routes.  Essentially, if a web request comes in to any of these paths  ( for example  http://localhost/cocos2d ), node will simply serve the files back to the requesting browser, just like IIS or Apache would.  These four lines will result in /cocos2d, /cocosDenshion, /classes and /resources folders having their files served, so when your HTML file requests /classes/cocos2d.js, the file will be returned.  This is how we will allow our user to download our scripts and resources.  In this particular, I am porting the class from this tutorial to run from Node, which is why we require a resources and cocosDenshion folder.

 

Next is a GET request handler for “/”.  In HTTP, there are two kinds of requests, GET ( urls ) and POST ( form submissions ).  In this line we are saying if someone requests our web root, our function is called, which simply sends the file index.html back.

 

A moment later, we set up another GET handler for the route (URL) /api/hello, which simply returns the string “Hello Cruel World”.  This is a very simple web service, and we will see it in action shortly.

 

Finally we start our server listening on port 3000, or whatever port the running environment forces us on, in case our host has such limitations.  At this point, we have a fully functioning web server. 

 

However, I made a few alterations to the last tutorial’s file layout to better be served by Node.  Our folder structure now looks like:

image

 

Don’t worry if you are missing a few folders ( .git and .idea for example ) or files ( package.json or Procfile ), we will covers those later.

 

I altered all the paths in cocos.js and MyFourthApp.js because cocos2d was moved to the classes folder.  Otherwise the code is pretty much unchanged from the last tutorial.  You can download the full source at the end of this post if you want to see the complete changes.

 

I did make a few small alterations though, beyond changing paths.  I added a reference to jQuery in index.html, like this:

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="classes/cocos2d.js"></script>

 

I also added the following line to cocos2d.js:

else { cc.setup("gameCanvas"); jQuery.get("/api/hello", function(data,textStatus,jqXHR){ cc.Log(data); });

 

So what exactly is this line of code doing?

 

Remember earlier in server.js where we added a route handler for /api/hello?  Well this is about as simple a REST based web request as you can make.  This uses jQuery to make an AJAX call to our server, which returns the string “Hello Cruel World”, which we log to the console.   

 

Why?  Well, absolutely no reason… yet.  But this is a very primitive example of something we are going to do in more complexity later on.  We can do processing on our node based server, and handle it in our cocos2D client.  Through this mechanism we can make up for the limitations of client side Javascript, or enable server side functionality.  You can easily request data from a server without having to reload your page.

 

 

Now you can run your server.  Open a command prompt, navigate to your project directory and type node server.js.  If all went well, there should be no error messages.  Now open up a web browser and navigate to http://localhost:3000 like this:

image

 

Here is your cocos2D application hosted in a custom Node server viewed in a browser, and if you look at the JavaScript console, you will see the “Hello Cruel World” message logged by cocos, but returned asynchronously from the server.  To shut down your server, simply press CTRL + C.

 

 

At this point we have a working web server, capable of hosting a cocos2D application ( and replacing the need for WAMP completely ), making successful, if simple, web services calls between the client and server.

 

You can download the full project right here.

 

Next up, we will look into a problem many web developers face… where the heck am I going to put this thing???

 

EDIT:  Next part is now up.

Programming


13. July 2012

I have a bit of a project I need to undertake in real life, that overlaps nicely with this site, so I am documenting the process here.

 

 

The nutshell version, I have a toddler and she is having trouble with transitions.  People have suggestion a This Then board, in terms of “Do This” “Then that” will happen.  Its remarkably simple over all, it is pretty much two pieces of velcro on a piece of cardboard and a bunch of pictures that we can stick to it.  I was about to have to print off a ton of pictures, scale them down, stick velcro to them and it dawned on me… this calls for an App!

 

 

See, I have a ton of devices around this place…  PCs, a Mac, a Galaxy Note, S3, Transformer, Playbook, iPhone, iPod and even an iPad that my daughter has pretty much claimed as her own.  So it only makes sense to implement this an application.  That said, supporting all of these platforms would be a pretty epic pain in the butt.  Also, I have very little desire to pay Apple 99$ a year just to put this app on her iPad, and I don’t want to be bothered with jailbreaking.

 

This is where my recent playing with HTML5 comes in extremely handy.  I am going to create it using a variety of technologies, include cocos2D, node/express and heroku.  The application itself is very simple, but the process is stuff that almost any moderately advanced web application is going to face.

 

First off, HTML5 is wonderful, but it has some serious limitations.  One such limitation is only having minimal local storage.  This is where your server comes in, and Node delivers in spades.  Another problem almost all web apps face is… where do I put this thing?  We will cover that as well.  Possibly at the end I will also covering delivering to device ( PhoneGap? Appcelerator? ), that’s a wait and see thing.

 

This isn’t exactly a tutorial series; this is something I have to accomplish, so I’ve decided to document the process as I go.  I wont always go into as much detail as I normally do with tutorials and I promise you, unless you have a toddler yourself, the end result wont be that exciting of a game.  However, you will see how to quickly make an HTML5 game in cocos2D, hosted in Node.js, developed quickly.  Hope you enjoy.

 

In fact, the first post is up.  This one covers hosting a cocos2D app ( our last tutorial on menus and music ) in a custom Node.js based server.

General


11. July 2012

 

In this tutorial we are going to cover playing sound effects and music files.  We are also going to implement a simple menu system to control everything.  The example sound effect and song are taken from the cocos2D HTML tests. 

 

First we need to preload our sound effect files.  Remember the preload in main.js?  Now we are going to actually use it.  Open up main.js and make the following change:

 

cc.AudioEngine.getInstance().init("mp3,ogg,wav");
   cc.Loader.shareLoader().preload([
    {type:"effect",src:"Resources/effect2"},
    {type:"bgm",src:"Resources/background"}
   ]);

 

Here we preload our song and sound effect for later playback.  It doesn’t have to be in this file, but it guarantees that it has happened when we need it.  You will need to add a pair of mp3 files in a subdirectory named Resources, background.mp3 and effect2.mp3.  Obviously you can use whatever files you want, but be sure not to add the file extension here. 

The out key call is the call to init(). This call initializes the AudioManager singleton.  The parameter are the supported file formats.  mp3, ogg and wav are the supported options.  This value determines what extension the loader will use when looking for your resources.  Each browser supports different file formats, so if you want to playback in as many browsers as possible, it is ideal to provide all three options.  For example, if you do not provide ogg, Chromium on Ubuntu will not play any sound.

 

Now lets take a look at MyFourthApp.js:

 

var MyFourthApp = cc.LayerColor.extend({
    init:function()
    {
        this.initWithColor(new cc.Color4B(0,0,0,255));
        var size = cc.Director.getInstance().getWinSize();


        cc.AudioEngine.getInstance().setEffectsVolume(0.5);
        cc.AudioEngine.getInstance().setBackgroundMusicVolume(0.5);

        var menuItem1 = new cc.MenuItemFont.create("Play Sound",this,this.playSound);
        var menuItem2 = new cc.MenuItemFont.create("Play Song",this,this.playSong);
        var menuItem3 = new cc.MenuItemFont.create("Stop Playing Song",this,this.stopPlayingSound);
        var menuItem4 = new cc.MenuItemFont.create("Exit",this,this.exit);

        menuItem1.setPosition(new cc.Point(size.width/2,size.height/2+50));
        menuItem2.setPosition(new cc.Point(size.width/2,size.height/2));
        menuItem3.setPosition(new cc.Point(size.width/2,size.height/2-50));
        menuItem4.setPosition(new cc.Point(size.width/2,size.height/2-100));

        var menu = cc.Menu.create(menuItem1,menuItem2,menuItem3,menuItem4);
        menu.setPosition(new cc.Point(0,0));

        this.addChild(menu);

        return this;
    },
    playSound:function(){
        cc.log("Playing sound");
        cc.AudioEngine.getInstance().playEffect("Resources/effect2");
    },
    playSong:function(){
        cc.log("Playing song");
        cc.AudioEngine.getInstance().playBackgroundMusic("Resources/background",false);
    },
    stopPlayingSound:function(){
        cc.log("Done playing song");
        if(cc.AudioEngine.getInstance().isBackgroundMusicPlaying())
        {
            cc.AudioEngine.getInstance().stopBackgroundMusic();
        }
    },
    exit:function(){
        document.location.href = "https://www.gamefromscratch.com";
    }
});


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

 

The guts of this are identical to the last tutorial, with the obvious exception of changed names.

The following two lines set the background volume for both music and effects to 50%.  As you can see, AudioManager is available as a singleton object, just like Director.

 

cc.AudioEngine.getInstance().setEffectsVolume(0.5);
cc.AudioEngine.getInstance().setBackgroundMusicVolume(0.5);

 

Next up we create 4 different MenuItemFont objects:

var menuItem1 = new cc.MenuItemFont.create("Play Sound",this,this.playSound); var menuItem2 = new cc.MenuItemFont.create("Play Song",this,this.playSong); var menuItem3 = new cc.MenuItemFont.create("Stop Playing Song",this,this.stopPlayingSound); var menuItem4 = new cc.MenuItemFont.create("Exit",this,this.exit);

 

MenuItemFont is one of the available types of menuitems ( there is also a sprite based menu item ) that compose a menu.  For each one, you specify the text to display, the owning container as well as a callback function that is called when the menu is selected.  We then position each menuitem relative to the center of the screen, each one placed 50 pixels apart.   We then create our Menu item by passing in a variable number of MenuItem, like this:

var menu = cc.Menu.create(menuItem1,menuItem2,menuItem3,menuItem4);

 

Finally we position our menu and add it to our layer.

 

Next we have our 4 different callback function.  cc.log simple logs whatever text out to the console.  So if you have the developer console open in Chrome, or Firebug on Firefox, you will see the following when the code is run:

image

 

cc.Log is an effective and easy way to keep track of your code’s execution without requiring the debugger.

 

In the event of selecting “Play Sound” the playSound() method is fired, which calls:

 

cc.AudioEngine.getInstance().playEffect("Resources/effect2");

 

This uses the AudioManager singleton to play our preloaded effect “effect2” in the folder “Resources” using the playEffect() method.

 

In the event of selecting “Play Song”, the playSong method is fired, which plays a song using the function:

 

cc.AudioEngine.getInstance().playBackgroundMusic("Resources/background",false);

 

If “Stop Playing Song” is selected, the stopPlayingSound method is fired, which checks if a song is currently playing and stops it if one is.  Like this:

 

if(cc.AudioEngine.getInstance().isBackgroundMusicPlaying())
        {
            cc.AudioEngine.getInstance().stopBackgroundMusic();
        }

 

Finally, in the event Exit is called, the app simply redirects the user to a great website. Smile

 

 

As always, you can download the full project ( including all audio files ) right here.

 

Here is our application in action:

 

 

Read Tutorial 6

Programming


5. July 2012

 

I have recently been contacted by members on the development teams of two (completely!) different HTML game related libraries for inclusion on the HTML 5 Development links page.

 

 

The first is the Pulse Engine, a traditional HTML5 Canvas based library.  Perhaps best of all, it has complete documentation (woot!).  I am taking a closer look at this when time permits, and will post something shortly.

 

 

 

The second is Clay.io, which is more of a supporting library.  It provides leaderboards, payment processing, social integration and more.  They are a commercial library and take a 20% cut of payments processed.  It is documented as well, and contains a developer sandbox to test in.  I do have one suggestion for the developers… make the features more prominent on your home page. The details were there, but they were below the fold ( on my 1920x1280 screen! ).  You will be amazed how many people you will lose because it was immediately obvious what service you provide! If you need to add these features to your game, clay.io is certainly a place to start.

 

 

If you have developed and HTML5 related game library, or are a big fan of a library I missed on my list, let me know! 

News


27. June 2012

image

 

OK, I will be the first to admit that there are a few hundred HTML5 3D game engines in development, so why draw any attention to this one?

 

Well, there are a couple very good reasons.

 

First off, star power.  There are pair of fairly successful people behind PlayCanvas.  The CEO is Will Eastcott, former tech director at Activision, who worked on Call of Duty, Grand Theft Auto and Max Payne.  The CTO is Dave Evans, formerly at Sony, and on the team responsible for PlayStation Home.  So, the people behind the company understand real game requirements and have the experience to pull it off.

 

Second, it’s a full tool chain.  This is perhaps the biggest single selling point, it contains a visual designer, importer for 3D Studios Max, Maya and Blender.  Plus of course the libraries you need to create a game, including dynamic lighting, shadow effects, bones/skinned animations, skeletal blending, 3D spatial audio, a component entity system for scripting and more.

 

So basically… they are going head to head with Unity, but focused on HTML5.  They have a demo section, but it is currently a bit underwhelming.

 

At this point, you may be wondering about cost…

During our closed beta, the PlayCanvas development environment will be free and unrestricted for all. When the closed beta ends, the vast majority of users will be able to continue to use PlayCanvas at no cost within some generous limitations. Pro accounts will be available on a subscription basis at a nominal monthly cost. These accounts will relax certain restrictions and unlock additional power-user oriented features in the interface.

 

Currently it is in closed beta, so you will have to contact them for more details.  They are however presenting at Google IO ( which is happening right now ), so perhaps we will have more details soon.

 

If this sounds interesting to you, head on over to playcanvas to learn more.

News


GFS On YouTube

See More Tutorials on DevGa.me!

Month List