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
You are currently viewing page 2 of 2 of this article. Click here to view the first page.

Contents

Hide contents

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

15 mins

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!

Contributors

Over 300 content creators. Join our team.