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

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! By Ray Wenderlich.

Leave a rating/review
Save for later
Share

Contents

Hide contents

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

15 mins

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

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!

Contributors

Over 300 content creators. Join our team.