How To Make a Cross-Platform Game with Cocos2D Javascript Tutorial: The Platforms

Ray Wenderlich

This is not a picture – it’s a game! Click to play!

Welcome back to our series on creating a cross-platform game using Cocos2D!

In the first part of this series, you learned how to make the simple game you see over on the right. That’s right, that’s not a picture it’s a game – click it to see for yourself!

So far you have the game code 100% complete, and you have it running on iOS and in debug mode for the web.

But what if you want to publish it to the web for real, run it on the Mac, or get it working on the Android? In this tutorial you’ll round it all up and get it fully working everywhere!

This project begins where the last project left off, so download the project where we left it off if you haven’t already.

Keep reading to fill out your platforms!

Deploying for the Web

I like to think of my Cocos2D-HTML5 setup in terms of “Debug mode” and “Release mode”.

Right now you have “Debug mode” working well. You’re linking to the easy-to-read and expanded Cocos2D source in the Cocos2DSimpleGame\Platform\HTML5 directory which you copied from the Cocos2D-HTML5 distribution.

This is great for debugging because if you ever have a problem you can step right into the Cocos2D-Javascript source code using your browser’s Javascript debugging capabilities. But it is not so good for release.

This is because there’s a lot of overhead in loading files on the web, so loading these directories containing tons of Cocos2D files isn’t very efficient. It’s much better for release to pack all of your Javascript code into a single file.

Luckily, this is quite easy with Cocos2D-Javscript! You can “minimize” all of the Cocos2D framework code and your own into one compressed file for release mode. It isn’t very easy to read, but loads real quickly.

Let’s try this out. Find the directory where you downloaded cocos2d-html5 to, find the cocos2d-html5-v2.x.x\lib\Cocos2d-html5-v2.x.x.min.js file, and copy it into your Cocos2DSimpleGame\Platform\HTML5 directory. If you’ve done it right it should look like the following:

Copying the minified Cocos2D-HTML5 Javascript file

This is the pre-minified version of the Cocos2D framework. Now, you just need to combine this with your own Javascript code into a single file.

While you’re there, also copy cocos2d-html5-v2.x.x\tools\compiler\compiler.jar into your Cocos2DSimpleGame\Platform\HTML5 directory. If you’ve done it right it should look like the following:

Copying the ant Javascript minimizer compiler

You need this file in order to perform the minimization process using a tool called ant.

If you’re a Java programmer, you will be well familiar with ant. If not, bear with me (or should I say “ant” with me?), as you can just modify the example below.

Create a new file Cocos2DSimpleGame\Platform\HTML5\build.xml and replace the contents with the following:

<?xml version="1.0"?>
<project name="Javascript compress project" basedir="." default="compile">
 
    <taskdef name="jscomp" classname="com.google.javascript.jscomp.ant.CompileTask"
             classpath="${basedir}/compiler.jar"/>
 
    <target name="compile">
        <jscomp compilationLevel="simple" warning="quiet"
                debug="false" output="${basedir}/../../Cocos2DSimpleGame-v0.1.js">
            <sources dir="${basedir}">
                <file name="Cocos2d-html5-v2.1.1.min.js" />
            </sources>
            <sources dir="${basedir}/../../Src">
                <file name="GameOver.js" />
                <file name="MainLayer.js" />
                <file name="resource.js" />
                <file name="main.js" />
            </sources>
        </jscomp>
     </target>
 </project>

Replace Cocos2d-html5-v2.1.1.min.js with the name of the file for the version of Cocos2D that you are using.

You don’t neeed to really understand what this is doing, except to notice that you have to list out each of the files in your project.

Next, open up a Terminal and swtich to your Cocos2DSimpleGame\Platform\HTML5 directory. Enter the command ant and hit enter. You should see something like the following:

localhost:HTML5 rwenderlich$ ant
Buildfile: /Users/rwenderlich/Desktop/Cocos2D-JS-Series/Part2/Cocos2DSimpleGame/
   Platform/HTML5/build.xml

compile:
   [jscomp] Compiling 5 file(s) with 40 extern(s)
   [jscomp] 0 error(s), 0 warning(s)

BUILD SUCCESSFUL
Total time: 5 seconds

You should also see a new file called Cocos2DSimpleGame\Cocos2DSimpleGame-v0.1.js. Now all you need to do is tell the framework to use this file.

To do this, open Cocos2DSimpleGame\cocos2d.js and replace the beginning part of the file (up to the event listener) with the following:

(function () {
    var d = document;
    var c = {
 
        menuType:'canvas',
        COCOS2D_DEBUG:2,
        box2d:false,
        chipmunk:false,
        showFPS:true,
        frameRate:60,
        loadExtension:true,
        tag:'gameCanvas',
 
        // RELEASE
        SingleEngineFile:'Cocos2DSimpleGame-v0.1.js',
 
        // DEBUG
        /*
        engineDir:'./Platform/HTML5/cocos2d/',
        appFiles:[
            './Src/resource.js',
            './Src/MainLayer.js',
            './Src/GameOver.js',
            './Src/main.js'
        ]*/
    };
 
    // Rest of file...

So instead of setting the engineDir and appFiles, you just specify one parameter – the SingleEngineFile.

And that’s it! Load index.html into your web browser and refresh to make sure it works.

Testing the minimized version

Also, if you’d like to deploy to an actual web server, now you can! All you need to do is copy these files/directories:

  • Art
  • cocos2d.js
  • Cocso2DSimpleGame-v0.1.js
  • index.html
  • logo.png
  • Sounds

In other words, everything but the Platform and Src directories. And if you want to try it out on my server, check it out!

Deploying for Mac

Remember how easy this was to get working for Cocos2D-iOS? Well it’s just as easy to get working for Cocos2D-Mac.

To do so, open Xcode and create a project with the OX X\cocos2d v2.x\cocos2d OS X with JavaScript template. Name the project Cocos2DSimpleGame, and save it to your Cocos2DSimpleGame\Platform\OSX directory.

Then, like you did for the iOS project, 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.

Adding folders to your Xcode project

Next, open Resources\main.js and replace it with the same contents as you did for the iOS version:

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();

Build and run, and now your game works on the Mac!

Cocos2D Javascript running on the Mac

Deploying for Android

There’s only one platform left – Android. I found this one the hardest to initially get working, but that could be just because I’m an Android n00b :]

This tutorial assumes you have some basic familiarity with Android development and that you have the Eclipse, the Android SDK, and the Android NDK installed. If you do not, check out this tutorial for more information.

Next you need to download the latest version of Cocos2D 2.X. At the time of writing, this is cocos2d-2.1beta3-x-2.1.1.

Unzip the file, then open a Terminal window and switch to the directory where you unzipped the file. Open create-android-project.sh and update the first two lines to point to where you installed your Android SDK and NDK:

# set environment paramters
NDK_ROOT_LOCAL="/home/laschweinski/android/android-ndk-r5"
ANDROID_SDK_ROOT_LOCAL="/home/laschweinski/android/android-sdk-linux_86"

Now run the create-android-project.sh script from the command line and you will get several prompts as to various input values. Let’s run through the prompts and what you need to input one-by-one:

  • Input package path: com.raywenderlich.Cocos2DSimpleGame
  • Target id: Choose from list or hit 1
  • Project name: Cocos2DSimpleGame

It should then create a Cocos2DSimpleGame directory for you. Copy the entire directory to your Cocos2DSimpleGame\Platform\Android folder.

There are two steps to building the project – compiling the C++ code with a command line script, and compiling the Java code with Eclipse. Let’s start with the C++ code.

Building the C++ code

Next, you need to update your build_native.sh script to fix up the paths and to copy the resources from your project’s root directory. Open Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\proj.android\build_native.sh and update the part toward the top of the file that sets up and echos the paths to the following:

COCOS2DX_ROOT="/Users/rwenderlich/Projects/iPhone/Libraries/cocos2d-2.1beta3-x-2.1.1"
APP_ROOT="$DIR/.."
APP_ANDROID_ROOT="$DIR"
BINDINGS_JS_ROOT="/Users/rwenderlich/Projects/iPhone/Libraries/cocos2d-2.1beta3-x-2.1.1/scripting/javascript/bindings/js"
RESOURCES_ROOT="$DIR/../../../../"
 
echo "NDK_ROOT = $NDK_ROOT"
echo "COCOS2DX_ROOT = $COCOS2DX_ROOT"
echo "APP_ROOT = $APP_ROOT"
echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT"
echo "RESOURCES_ROOT = $RESOURCES_ROOT"

Except replace the hardcoded directoreis I have here to where you actually have your copy of Cocos2D-X.

Then add these lines toward the bottom of the file, right after the “copy icons” section:

# copy bindings/*.js into assets' root
cp -f "$BINDINGS_JS_ROOT"/*.js "$APP_ANDROID_ROOT"/assets
 
# copy resources
cp -rf "$RESOURCES_ROOT/Art" "$APP_ANDROID_ROOT"/assets
cp -rf "$RESOURCES_ROOT/Sounds" "$APP_ANDROID_ROOT"/assets
cp -rf "$RESOURCES_ROOT/Src" "$APP_ANDROID_ROOT"/assets

These copy your project resources from the root directory into the assets directory – a special directory in Android that gets added to your binary.

Now, go to your Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\proj.android\ directory in Terminal and run build_native.sh. It should compile Cocos2D-X and generate libcocos2d.a, libcocosdenshion.a, and other libraries. You will also see your resources are now in the assets folder.

Building the Java code

To build the Java code, you’ll add the Cocos2D-X Java library to Eclipse and then your project.

To do this, start Eclipse and go to File\New\Other. Choose Android\Android Project from Existing Code, and click Next. For root directory, click Browse, navigate to your cocos2d-xxx/cocos2dx/platform/android/java directory, click Open, Select All, and Finish.

That imported the Cocos2D-X Java library. Now to add your project, go to go to File\New\Other again, choose Android\Android Project from Existing Code, and click Next. For root directory, click Browse, navigate to your Cocos2DSimpleGame\Platform\Android directory, click Open, Select All, and Finish.

If all goes well, your project directory should look like this right now:

Eclipse package explorer for Cocos2D-X Javascript project

I had to do two final things to get this to compile. Right click on Cocos2DSimpleGame and choose Properties. Then go to Android and in the Library section click Add, and select the Cocos2D-X Java library.

Adding Cocos2D-X Library dependency for Cocos2D-X Javascript Project in Eclipse

Finally, right click AndroidManifest.xml and choose Open With\Android Common XML editor. Change the minSdkVerison to 1:

<uses-sdk android:minSdkVersion="1"/>

And modify the application tag to remove any references to the app icon:

<application android:label="@string/app_name">

At this point you can build and run the hello world app on your device, but it won’t load your Javascript code yet. That’s coming next!

Running the Javascript

Just like you did for the other platforms, you need to add some “starter” Javascript. So create a new file Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\Resources\Cocos2DSimpleGame-jsb.js, and replace the contents with the following:

require("jsb.js");
 
var MW = MW || {};
 
var appFiles = [
    'Src/resource.js',
    'Src/MainLayer.js',
    'Src/GameOver.js'
];
 
cc.dumpConfig();
 
for( var i=0; i < appFiles.length; i++) {
    require( appFiles[i] );
}
 
var director = cc.Director.getInstance();
director.setDisplayStats(true);
 
// set FPS. the default value is 1.0/60 if you don't call this
director.setAnimationInterval(1.0 / 60);
 
var winSize = director.getWinSize();
var centerPos = cc.p( winSize.width/2, winSize.height/2 );
 
// create a scene. it's an autorelease object
var mainScene = MainLayer.scene();
 
// run
director.runWithScene(mainScene);

This is very similar to the main.js file you created for Cocos2D Mac and iOS.

Next, open Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\Classes\AppDelegate.cpp and replace the contents with the following:

#include "AppDelegate.h"
 
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
#include "ScriptingCore.h"
#include "generated/cocos2dx.hpp"
#include "cocos2d_specifics.hpp"
#include "js_bindings_chipmunk_registration.h"
#include "js_bindings_ccbreader.h"
USING_NS_CC;
using namespace CocosDenshion;
 
AppDelegate::AppDelegate()
{
}
 
AppDelegate::~AppDelegate()
{
    CCScriptEngineManager::sharedManager()->purgeSharedManager();
}
 
bool AppDelegate::applicationDidFinishLaunching()
{
    // initialize director
    CCDirector *pDirector = CCDirector::sharedDirector();
    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
    pDirector->setProjection(kCCDirectorProjection2D);
 
    // Set the design resolution
    CCEGLView::sharedOpenGLView()->setDesignResolutionSize(480, 320, kResolutionExactFit);
 
    // turn on display FPS
    pDirector->setDisplayStats(true);
 
    // set FPS. the default value is 1.0/60 if you don't call this
    pDirector->setAnimationInterval(1.0 / 60);
 
    ScriptingCore* sc = ScriptingCore::getInstance();
    sc->addRegisterCallback(register_all_cocos2dx);
    sc->addRegisterCallback(register_cocos2dx_js_extensions);
    sc->addRegisterCallback(register_CCBuilderReader);
    sc->addRegisterCallback(jsb_register_chipmunk);
    sc->start();
 
    CCScriptEngineProtocol *pEngine = ScriptingCore::getInstance();
    CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
    ScriptingCore::getInstance()->runScript("Cocos2DSimpleGame-jsb.js");
 
    return true;
}
 
void handle_signal(int signal) {
    static int internal_state = 0;
    ScriptingCore* sc = ScriptingCore::getInstance();
    // should start everything back
    CCDirector* director = CCDirector::sharedDirector();
    if (director->getRunningScene()) {
        director->popToRootScene();
    } else {
        CCPoolManager::sharedPoolManager()->finalize();
        if (internal_state == 0) {
            //sc->dumpRoot(NULL, 0, NULL);
            sc->start();
            internal_state = 1;
        } else {
            sc->runScript("hello.js");
            internal_state = 0;
        }
    }
}
 
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
    CCDirector::sharedDirector()->stopAnimation();
    SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
    SimpleAudioEngine::sharedEngine()->pauseAllEffects();
}
 
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
    CCDirector::sharedDirector()->startAnimation();
    SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
    SimpleAudioEngine::sharedEngine()->resumeAllEffects();
}

This is just some boilerplate code that starts up Cocos2D Javascript. I got it from one of the samples that ccomes with Cocos2D-X.

Finally, you need to make a few changes to the build scripts in order to pull in the Javascript bindings libraries. Open Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\proj.android\jni\Android.mk and replace the contents with the following:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := game_shared

LOCAL_MODULE_FILENAME := libgame

LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   ../../Classes/HelloWorldScene.cpp

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static
LOCAL_WHOLE_STATIC_LIBRARIES += spidermonkey_static
LOCAL_WHOLE_STATIC_LIBRARIES += scriptingcore-spidermonkey

LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT

include $(BUILD_SHARED_LIBRARY)

$(call import-module,cocos2dx)
$(call import-module,CocosDenshion/android)
$(call import-module,external/chipmunk)
$(call import-module,scripting/javascript/spidermonkey-android)
$(call import-module,scripting/javascript/bindings)

Don’t worry if you don’t understand this stuff – it’s just telling the compiler which libraries to bring in.

Open Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\proj.android\jni\Application.mk and replace the contents with the following:

APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -DCOCOS2D_JAVASCRIPT=1
APP_CPPFLAGS += -DCOCOS2D_DEBUG=1 -DCC_ENABLE_CHIPMUNK_INTEGRATION=1

Finally, go to your Cocos2DSimpleGame\Platform\Android\Cocos2DSimpleGame\proj.android\ directory in Terminal and run build_native.sh again. It should compile everything again but bring in your updated AppDelegate and the bindings code this time.

Once it’s finished, refresh your Eclipse and build and run – and the app works on your Android!

Cocos2D-X Javascript game working on Android

Note: The Android version is a little dodgy on my test device. The music stops after the first reset of the level, and sometimes it hangs completely! I have no clue why this is, so if anyone else is more experienced with Android and Cocos2D-X development and does know please let me know :]

Where To Go From Here?

Here is the final example project from this tutorial series.

Congratulations – you have now made a cross platform game using Cocos2D Javascript Bindings and got it working on iOS, HTML, Android, and the Mac – all using the same code!

What’s more, but you have a well thought out directory structure that makes working across the different platforms a breeze.

I hope this tutorial has piqued your interest about Cocos2D Javascript development. If you would like to see more tutorials about Cocos2D Javascript please let me know.

In the meantime, if you have any comments or questions, please join the forum discussion below!

Ray Wenderlich

Ray is part of a great team - the raywenderlich.com team, a group of over 100 developers and editors from across the world. He and the rest of the team are passionate both about making apps and teaching others the techniques to make them.

When Ray’s not programming, he’s probably playing video games, role playing games, or board games.

User Comments

16 Comments

[ 1 , 2 ]
  • Hi,
    Great tutorial.
    I have a working cordova project can I use the same for working with Cocos platform or the complete code base need to be changed.
    paddy111padam
[ 1 , 2 ]

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Our Books

Our Team

Swift Team

... 13 total!

iOS Team

... 53 total!

Android Team

... 7 total!

OS X Team

... 11 total!

Sprite Kit Team

... 9 total!

Unity Team

... 6 total!

Unreal Engine Team

... 2 total!

Articles Team

... 9 total!