How To Make a Cross-Platform Game with Cocos2D Javascript Tutorial: Getting Started

In this tutorial, you will port the raywenderlich.com classic Ninjas Going Pew-Pew game to Cocos2D-Javascript. I like implementing this game when learning new frameworks because it’s simple, but covers the most important aspects of making a game. By Ray Wenderlich.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 5 of this article. Click here to view the first page.

Gratuitious Music and Sound Effects

You’re pretty close to having a workable (but extremely simple) game now. You just need to add some sound effects and music (since what kind of game doesn’t have sound!) and some simple game logic.

First, update Cocos2DSimpleGame\Src\resource.js to add the sound effects:

var dirArt = "Art/";
var dirSounds = "Sounds/";

var s_player = dirArt + "player.png";
var s_monster = dirArt + "monster.png";
var s_projectile = dirArt + "projectile.png";

var s_bgMusic = dirSounds + "background-music.mp3";
var s_bgMusicOgg = dirSounds + "background-music.ogg";
var s_bgMusicCaf = dirSounds + "background-music.caf";

var s_shootEffect = dirSounds + "pew-pew-lei.mp3";
var s_shootEffectOgg = dirSounds + "pew-pew-lei.ogg";
var s_shootEffectWav = dirSounds + "pew-pew-lei.wav";

var g_ressources = [

    {type:"image", src:s_player},
    {type:"image", src:s_monster},
    {type:"image", src:s_projectile},

    {type:"sound", src:s_bgMusic},
    {type:"sound", src:s_bgMusicOgg},
    {type:"sound", src:s_bgMusicCaf},

    {type:"sound", src:s_shootEffect},
    {type:"sound", src:s_shootEffectOgg},
    {type:"sound", src:s_shootEffectWav}

];

Note that both the background music and sound effects are each saved in three different formats: mp3, ogg, and wav. This is because not all browsers support all formats, so by adding all three we will have the highest possible chance of the player being able to hear something. Cocos2D will detect what the browser supports and use the appropriate file - as long as they have the same filename.

Note: If you're wondering how to convert between these formats, here's what I do:

  • I usually start with a WAV.
  • I then use iTunes to convert to an MP3. To do this, go to iTunes Preferences\General\Import Settings and change Import Using to MP3 Encoder. Then you can import a WAV into iTunes, and right click it and select Create MP3 Version to create a MP3.
  • I then convert the MP3 to an OGG using oggenc. I used this guide as a howto for installing it.

Note: If you're wondering how to convert between these formats, here's what I do:

  • I usually start with a WAV.
  • I then use iTunes to convert to an MP3. To do this, go to iTunes Preferences\General\Import Settings and change Import Using to MP3 Encoder. Then you can import a WAV into iTunes, and right click it and select Create MP3 Version to create a MP3.
  • I then convert the MP3 to an OGG using oggenc. I used this guide as a howto for installing it.

Now, time to play these effects. Back in Cocos2DSimpleGame\Src\MainLayer.js add this to the top of the file:

var audioEngine = cc.AudioEngine.getInstance();

This gets a global reference to the audio engine so you can use it later. Then add this line to the end of onEnter:

audioEngine.playMusic(s_bgMusic, true);

And add this to the end of locationTapped:

audioEngine.playEffect(s_shootEffect);

Save the file and refresh your browser, and now you should have some groovy tunes!

Winning and Losing

To wrap up, let's create a new scene and layer that will serve as your “You Win” or “You Lose” indicator. Create a new file Cocos2DSimpleGame\Src\GameOver.js and replace the contents with the following:

var GameOver = cc.LayerColor.extend({

    _won:false,

    ctor:function() {
        this._super();
        cc.associateWithNative( this, cc.LayerColor );
    },

    onEnter:function () {

        this._super();

        var director = cc.Director.getInstance();
        var winSize = director.getWinSize();
        var centerPos = cc.p( winSize.width/2, winSize.height/2 );

        var message;
        if (this._won) {
            message = "You Won!";
        } else {
            message = "You Lose :[";
        }

        var label = cc.LabelTTF.create(message, "Arial", 32);
        label.setColor(cc.c3b(0, 0, 0));
        label.setPosition(winSize.width/2, winSize.height/2);
        this.addChild(label);

        this.runAction(cc.Sequence.create(
            cc.DelayTime.create(3),
            cc.CallFunc.create(function(node) {
                var scene = MainLayer.scene();
                cc.Director.getInstance().replaceScene(scene);
            }, this)
        ));

    }
});

GameOver.create = function (won) {
    var sg = new GameOver();
    sg._won = won;
    if (sg && sg.init(cc.c4b(255, 255, 255, 255))) {
        return sg;
    }
    return null;
};

GameOver.scene = function (won) {
    var scene = cc.Scene.create();
    var layer = GameOver.create(won);
    scene.addChild(layer);
    return scene;
};

This is a layer that contains a label in the middle of the screen (cc.LabelTTF) that contains the message. An action is created to wait three seconds, and then transition back to the MainLayer.

To use this new scene, go back to Cocos2DSimpleGame\Src\MainLayer.js and make these changes:

// Add this new instance variable to the top of the file
_monstersDestroyed:0,

// Add inside update, right after monster.removeFromParent():
this._monstersDestroyed++;
if (this._monstersDestroyed >= 2) {
    var scene = GameOver.scene(true);
    cc.Director.getInstance().replaceScene(scene);
}

// Add inside addMonster, right after node.removeFromParent():
var scene = GameOver.scene(false);
cc.Director.getInstance().replaceScene(scene);

Finally, since you added a new file you need to reference it in cocos2d.js. So open Cocos2DSimpleGame\cocos2d.js and modify the appFiles array to the following:

appFiles:[
    './Src/resource.js',
    './Src/MainLayer.js',
    './Src/GameOver.js',
    './Src/main.js'
]

And that's it! Save the file and refresh your browser, and now you now have a complete Cocos2D Javascript game!

You won!

Just One More Thing...

The whole point of Cocos2D-Javascript is that it's cross-platform, right?

Let me show you how you can get this same code running on the iPhone in less than 5 minutes :]

Well - assuming you have the latest version of Cocos2D-iOS already installed that is. If not, download the latest unsable 2.X version (2.1-rc0a) and install the templates.

Note: After downloading the latest version of Cocos2D you can install the templates by running the following commands from a Terminal:

cd ~/Downloads/cocos2d-iphone-2.1-rc0
./install-templates.sh -f -u

Note: After downloading the latest version of Cocos2D you can install the templates by running the following commands from a Terminal:

cd ~/Downloads/cocos2d-iphone-2.1-rc0
./install-templates.sh -f -u

Then create a new project in Xcode using the iOS\cocos2d v2.x\cocos2d iOS with JavaScript template. Name the new project Cocos2DSimpleGame and save it in the Cocos2DSimpleGame\Platform\iOS folder.

Then, inside Finder find your Cocos2DSimpleGame folder, select the Art, Sounds, and Src folders, and drag them into your Xcode project. Important: In the popup that appears, select Create folder references for any added folders, and set the rest of the options like the screenshot below:

Adding folders to your Xcode project

If you did it correctly, your folders should be blue in Xcode like the screenshot below. If they are yellow, you selected "groups" instead - remove them and try again.

Make sure the folders are blue

Next, open Resources\main.js and replace the contents with the following:

require("jsb.js");
require("Src/resource.js");
require("Src/MainLayer.js");
require("Src/GameOver.js");

director = cc.Director.getInstance();
winSize = director.getWinSize();
centerPos = cc.p( winSize.width/2, winSize.height/2 );

function run()
{
    director.runWithScene( MainLayer.scene() );
}

run();

Here you load your game files, set up the global variables, and run the main scene.

And that's it! Build and run, and now you have the same code running on your iPhone - but using native Cocso2D-iPhone!

Cocos2D Javascript project running on iPhone

Note: Note that if anything is wrong with your Javascript code, sometimes you'll see an error in the Xcode console, but many times default Xcode will give you no useful error messages at all.

This is one of the reasons I find developing initially with Cocos2D-HTML5 much easier.

Note: Note that if anything is wrong with your Javascript code, sometimes you'll see an error in the Xcode console, but many times default Xcode will give you no useful error messages at all.

This is one of the reasons I find developing initially with Cocos2D-HTML5 much easier.

Contributors

Over 300 content creators. Join our team.