Setting up your app

In this section, you will learn how to set up the skeleton file and folder structure of a basic Cocos2d-html5 game. Later, we will build on this foundation, but for now, we want your app to look like this:


The skeleton file and folder structure for your app.

Let's get started. To be able to preview your app in Ripple, you'll need to create your project's folder structure within the RippleSites folder. If you have not set up a RippleSites folder yet, follow the instructions at Access your project in Ripple.

In your RippleSites folder, create a new folder and give it a project name. Create three more folders in that folder, and name them cocos, css, and js.

You can now create the required files using a text editor. Let's look at each file individually.

Create config.xml

The config.xml file defines the application properties: it defines the BlackBerry WebWorks namespace; it provides the app name, description, and start page; and it specifies features and functionality the app can access. For this sample app, we provide you with the contents of the config.xml file. For information on setting up the config.xml file in your future apps, see Create your config.xml file.

Copy and paste the following into your text editor, and then save the file as config.xml in your main project folder.

<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets"
        xmlns:rim="http://www.blackberry.com/ns/widgets"
        id="com.oros.boxquest"
        version="1.0.0.0">

    <name>BoxQuest</name>
    <author>Oros</author>
    <content src="index.html" />

    <feature id="blackberry.app.orientation">
        <param name="mode" value="landscape" />
    </feature>
</widget>

Create styles.css

We want your app to use styles, and we can apply them to the main <body> element of index.html using the styles.css file. To make sure the app uses the entire screen, we'll set the height and width to 100% and set padding and margin values to 0. We also define values for the cursor, font, and background color.

Copy and paste the following content into your text editor, and then save the file as styles.css in your css folder.

body {
    background-color: black;
    cursor: default;
    font-family: sans-serif;
    height: 100%;
    bodymargin: 0;
    padding: 0;
    width: 100%;
}

Create index.html

The index.html file is the start page of your app, as indicated by the content element in the config.xml file. The sample below uses BlackBerry WebWorks APIs. For API usage information and reference materials, see Using BlackBerry WebWorks APIs.

The sample file also defines a custom script object that loads Cocos2d-html5 into the app. This object requires the id property cocos2d-html5. The box2d Boolean variable is set to false because we load Box2dWeb physics into the app later, using a different file. The engineDir file path shows where we place the Cocos2d-html5 framework, and the appFiles array contains any JavaScript files we want to import into the app.

Also note the file path that indicates jsloader.js, which is a component of the Cocos2d-html5 framework.

Copy and paste the following content into your text editor, and then save the file as index.html in your main project folder.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            (function () {
                var meta = document.createElement('meta');
                meta.setAttribute('name', 'viewport');
                meta.setAttribute('content', 'initial-scale=' + (1.0 / 
                     window.devicePixelRatio) + ',user-scalable=no');
                document.getElementsByTagName('head')[0]
                        .appendChild(meta);
            }());
        </script>
        <link type="text/css" rel="stylesheet" href="css/styles.css" />
    </head>
    <body>
        <canvas id="ccCanvas"></canvas>
        <script type="text/javascript" 
                 src="local:///chrome/webworks.js">
        </script>
        <script type="text/javascript">
            function onwebworksready() {
                document.removeEventListener('webworksready', 
                         onwebworksready, false);

                var script = document.createElement('script');
                script.id = 'cocos2d-html5';
                script.c = {
                    box2d: false,
                    engineDir: './cocos/cocos2d/',
                    appFiles: [
                        './js/SceneStart.js'
                    ]
                };
                script.src = script.c.engineDir + 
                             'platform/jsloader.js';
                document.ccConfig = script.c;
                document.body.appendChild(script);
            }

            function ondomcontentloaded() {
                window.removeEventListener('DOMContentLoaded', 
                       ondomcontentloaded, false);
                document.addEventListener('webworksready', 
                         onwebworksready, false);
            }

            window.addEventListener('DOMContentLoaded', 
                   ondomcontentloaded, false);
        </script>
    </body>
</html>

Create main.js

Back in index.html, we defined a custom script object that injected jsloader.js (a component of the Cocos2d-html5 framework we haven't added yet) into the document. When this action is complete, the main.js file automatically loads into the document, and this file you need to create yourself. In your main project folder, create a file named main.js and open it in your text editor.

First, we extend the cc.Application class to define the actions of your app as it is loaded. We do this within the ctor function. When you extend any Cocos2d-html5 class, you need to call that object’s super function.

We also set this.startScene equal to SceneStart, which we will define when you create the SceneStart.js file.

/*global cc, SceneStart */

var ccApplication = cc.Application.extend({
    ctor: function () {
        this._super();
        this.startScene = SceneStart;

Next, we set the debug level for your app, where 0 indicates no logging, 1 indicates minimal logging, and 2 indicates full logging.

        cc.COCOS2D_DEBUG = 0;
        cc.initDebugSetting();

Now we call the setup function on your <canvas>. After calling the setup function, we set three additional CSS styles to make sure that your <canvas> and the <div> that contains it remain properly styled.

        cc.setup('ccCanvas', window.innerWidth, window.innerHeight);
        document.querySelector('#Cocos2dGameContainer').style
          .overflow = 'hidden';
        document.querySelector('#Cocos2dGameContainer').style
          .position = 'fixed';
        document.querySelector('#ccCanvas').style.position = 'fixed';

The next step is to define your onloading and onload functions. These functions are essentially the same across all Cocos2d-html5 apps. We call the preload function with an empty array, because we don’t have any assets to preload yet, and then we close the ctor function.

After the preload function is complete, it starts the next phase of initialization automatically, which involves creating and presenting your scene. To accomplish this, we define the applicationDidFinishLaunching function.

	    cc.Loader.getInstance().onloading = function () {
            cc.LoaderScene.getInstance().draw();
        };

        cc.Loader.getInstance().onload = function () {
            cc.AppController.shareAppController()
              .didFinishLaunchingWithOptions();
        };

        cc.Loader.getInstance().preload([
        ]);
    },

    applicationDidFinishLaunching: function () {
        var director = cc.Director.getInstance();
        director.setDisplayStats(true);
        director.runWithScene(new this.startScene());
        return true;
    }
});

All the code we entered so far only defines the class. We also need a way to initiate the ctor function when main.js loads. To do this, we add a final line, setting your ccMain variable to a new ccApplication object.

var ccMain = new ccApplication();

Save the file and we will come back to it later.

Create SceneStart.js

Back in main.js, we defined this.startScene to be equal to SceneStart. SceneStart is defined in the SceneStart.js file, which you will create now. In your js folder, create a file named SceneStart.js and open it in your text editor.

When main.js is preloaded, it invokes SceneStart.onEnter and creates an instance of LayerStart to add to your scene. To begin, we define LayerStart as an extension of Layer. As we saw in main.js, the first step to extending anything is to call this._super(). We’re not adding any content yet, so all we do is return true to indicate success.

/*global cc */

var LayerStart = cc.Layer.extend({
    ctor: function () {
        this._super();
        return true;
    }
});

Now your SceneStart variable needs a similar definition. Here, we initialize the variable using this.super() and we add an instance of LayerStart to the scene.

var SceneStart = cc.Scene.extend({
    onEnter: function () {
        this._super();
        this.addChild(new LayerStart());
    }
});

The current file is basic, but it will grow as you add more content to your app. Save the file.

Fill the cocos folder

You may notice that your cocos folder is still empty. This folder is where we will store the Cocos2d-html5 framework for your app to access, as we specified in the index.html file.

Unzip the Cocos2d-html5 framework you downloaded earlier from GitHub and place the cocos2d and CocosDenshion folders in your cocos folder.

Test your app in the Ripple emulator

You now have a complete skeleton Cocos2d-html5 app. Let's run it in the Ripple emulator to make sure everything is working.

  1. Open Google Chrome.
  2. Click the Ripple icon next to the address bar.
  3. Click Start Ripple Services.
  4. In the address bar, type http://localhost:9910/ followed by your project folder and start page. Using the example file and folder structure, it would be: http://localhost:9910/<your project>/index.html
  5. Click Ripple > Enable.

You should see the following blank screen.


The app running in the Ripple emulator.

Don't worry, in the following section you will learn how to fill this screen with a background and sprites.

Last modified: 2014-03-10



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus