The default Cocos 2d-x project (see Tutorial: How to Create a New Cocos 2d-x Game Project) displays the words “Hello World” to your screen along with the Cocos 2d-x logo:

Hello World

If we open the project with Visual Studio (navigate to your project’s directory, go into the proj.win32 folder and double click on the Microsoft Visual Studio Solution that shares the same name as your project), you will see the following files in the Solution Explorer window (we only care about the ones in the src subfolder):

Solution Explorer - Hello World

Let’s see what they all do!

Namespace Cocos2d

All of these .cpp files have the line USING_NS_CC, which basically means “Using Namespace Cocos2d”. It’s so we don’t have to preface functions in the Cocos2d namespace with Cocos2d:: all the time.

AppDelegate.h

#ifndef  _APP_DELEGATE_H_
#define  _APP_DELEGATE_H_

#include "cocos2d.h"

/**
@brief    The cocos2d Application.

The reason for implement as private inheritance is to hide some interface call by Director.
*/
class  AppDelegate : private cocos2d::Application
{
public:
    AppDelegate();
    virtual ~AppDelegate();

    virtual void initGLContextAttrs();

    /**
    @brief    Implement Director and Scene init code here.
    @return true    Initialize success, app continue.
    @return false   Initialize failed, app terminate.
    */
    virtual bool applicationDidFinishLaunching();

    /**
    @brief  The function be called when the application enter background
    @param  the pointer of the application
    */
    virtual void applicationDidEnterBackground();

    /**
    @brief  The function be called when the application enter foreground
    @param  the pointer of the application
    */
    virtual void applicationWillEnterForeground();
};

#endif // _APP_DELEGATE_H_

Naturally, this is a header function for the AppDelegate class defined in AppDelegate.cpp. It declares the following functions:

  • AppDelegate() — Constructor for the AppDelegate class
  • virtual ~AppDelegate() — Destructor for the AppDelegate class
  • virtual void initGLContextAttrs() — This function is responsible for implementing an OpenGL (Open Graphics Library) context so you can use OpenGL to render your 2D and 3D graphic images on any platform
  • virtual bool applicationDidFinishLaunching() — Launches and initializes your app and returns true if that launch was successful and false if it was not
  • virtual void applicationDidEnterBackground() — Tells the application what to do if it starts running in the background (is no longer on the screen). E.g. If the user gets a phone call or switches to a different app
  • virtual void applicationWillEnterForeground() — Tells the application what to do if it starts running in the foreground again (is back on the screen). E.g. If the user returns to the app after a phone call

AppDelegate.cpp

#include "AppDelegate.h"
#include "HelloWorldScene.h"

USING_NS_CC;

AppDelegate::AppDelegate() {

}

AppDelegate::~AppDelegate() 
{
}

//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
    //set OpenGL context attributions,now can only set six attributions:
    //red,green,blue,alpha,depth,stencil
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};

    GLView::setGLContextAttrs(glContextAttrs);
}

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
        glview = GLViewImpl::create("My Game");
        director->setOpenGLView(glview);
    }

    // turn on display FPS
    director->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0 / 60);

    // create a scene. it's an autorelease object
    auto scene = HelloWorld::createScene();

    // run
    director->runWithScene(scene);

    return true;
}

// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
    Director::getInstance()->stopAnimation();

    // if you use SimpleAudioEngine, it must be pause
    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();

    // if you use SimpleAudioEngine, it must resume here
    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}

This file implements the functions declared in AppDelegate.h:

  • AppDelegate::AppDelegate() — Builds an AppDelegate() object with uninitialized values
  • AppDelegate::~AppDelegate() — The destructor function that gets called when an AppDelegate object goes out of scope. Note that just because this function is empty doesn’t mean it won’t ever execute any code. The compiler can add code to the function in order to call the destructors of the base class and non-static data members if it needs to
  • void AppDelegate::initGLContextAttrs() — Allows you to set how many bits should be used to represent each of the following OpenGL attributes:
    { red, green, blue, alpha, depth, stencil }

    • Red, green, and blue refer to the colors displayed on your screen
    • Alpha usually refers to transparency
    • Depth refers to how far away from the viewer and “into” your screen the pixel should be. For instance, if you have two pixels A and B with the same (x,y) coordinate but A has a shallower depth than B, then there is no need to draw B because it would be hidden by A anyway, thereby speeding up your program
    • Stencil allows you to tell OpenGL which pixels to draw and which ones to mask. In the example below, the black areas have been masked out by setting the stencil buffer to 0 (false) in those areas. Where the main picture shows through, the stencil buffer has been set to 1 (true):
      Masked Dune
  • bool AppDelegate::applicationDidFinishLaunching() — Launches your app by creating and initializing a director object and a scene object. (Note: The string “My Game” is the title that appears on the left side of the gray bar at the top of your application next to the Cocos 2d icon. See the picture at the top of this tutorial for a reference)
    • Director — This object is a Singleton, meaning your program has exactly one of it. The director object initializes an OpenGL context to create and handle your application’s window/screen, and it also controls how/when to execute scenes.
    • Scene — A scene is a “room” that holds everything that gets drawn on your screen. E.g. The first scene in your app might contain a picturesque background and a menu

    It also displays the FPS (Frames Per Second) information on your screen (comment out the line director->setDisplayStats(true); if you don’t want it to display that information). The FPS is set to 1/60 of a second—any slower and the human eye can detect lag but any faster is pointless since it’s too fast for the eye to see. Finally, a scene is created and the director object is told to run it (note that the line Director::getInstance()->runWithScene(scene) should only be used to run a scene at the start of a game, since Cocos will run scenes by itself after that)

  • void AppDelegate::applicationDidEnterBackground() — Tells the application to stop drawing images to the screen (stopAnimation) because your application is now in the background (no longer on screen). If you choose the option to pause instead, the application will continue to draw, just at a very low FPS
  • void AppDelegate::applicationWillEnterForeground() — Tells the application to start drawing images again because the user has brought it back to the foreground (on screen)

HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

class HelloWorld : public cocos2d::Layer
{
public:
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();
    
    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__

This is a header function for the HelloWorldScene class defined in HelloWorldScene.cpp. Its purpose is to create a scene for your game. It declares the following functions:

  • static cocos2d::Scene* createScene() — Creates a scene (with a single layer) and returns a pointer to it
    • Layers — “Shelves” within a scene that usually contain objects. Each layer is assigned a depth (see AppDelegate.cpp for definition) that can affect image rendering or object interactions
  • virtual bool init() — Initializes HelloWorld’s scene to contain a layer, a quit (power) button within the application (not the red button in the upper-right corner), the text “Hello World” and the Cocos 2d logo
  • void menuCloseCallback(cocos2d::Ref* pSender) — Actually closes the program when a user presses the quit (power) button (located within the application)
  • CREATE_FUNC(HelloWorld) — Is a macro that defines the create() method for your class. The actual code for the macro is as follows:
    #define CREATE_FUNC(__TYPE__)
    static __TYPE__* create()
    {
        __TYPE__ *pRet = new(std::nothrow) __TYPE__();
        if (pRet && pRet->init())
        {
            pRet->autorelease();
            return pRet;
        }
        else
        {
            delete pRet;
            pRet = NULL;
            return NULL;
        }
    }
    

    Basically, the macro creates a new HelloWorld instance (__TYPE__), calls its init() function (note that without this macro, init() is never called!), and calls autorelease().

    • __TYPE__ — This is the name of the class the macro is in (in this case, HelloWorld)
    • std::nothrow — Means that if the function fails to create a new object of type __TYPE__, then it should return a null pointer instead of throwing an exception
    • autorelease() — Even though we create new objects using the keyword new, we never want to delete them! That’s because Cocos 2d uses reference counters to keep track of when to release (delete) objects. The autorelease() method is a delayed release that ensures that if our instance ever has zero references (pointers) holding on to it, then its memory will be released once the current code block returns. It should be used whenever a function creates (using new, alloc, copy, or mutableCopy) an object that will be returned to the calling function (meaning the object can’t be released by the function that created it—even though that particular function doesn’t need it anymore—since the calling function still needs to use it). See Cocos2d’s Advanced Memory Management Programming Guide for more information on how memory management works in Cocos2d

HelloWorldScene.cpp

#include "HelloWorldScene.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
    
	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
    
    // position the label on the center of the screen
    label->setPosition(Vec2(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(label, 1);

    // add "HelloWorld" splash screen"
    auto sprite = Sprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(sprite, 0);
    
    return true;
}


void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}

This file implements the functions declared in HelloWorldScene.h.

  • Scene* HelloWorld::createScene() — Creates a scene and a layer (a HelloWorld class instance, since HelloWorld inherits from Layer) which it sets as a child of that scene. It then returns a pointer to the scene
  • bool HelloWorld::init() — HelloWorld inherits from Layer, so the first thing this function calls is Layer’s init() method. If that doesn’t work, we return false since we can’t initialize HelloWorld if we can’t even initialize Layer. Then it creates variables to store the screen size and the screen’s coordinate system’s origin (used for setting the position of objects). It also creates a quit (power) button within the application to allow users to close it (note that this is not the red “X” button in the upper-right corner of the screen) and sets its location. It then creates a menu that contains the quit button as a child object and sets its position on the screen. Next, the function creates a “Hello World” label (Label::createWithTTF(text, font, font-size)), sets its position on the screen, and adds it as a child of the HelloWorld object. Finally, it does the same thing with a sprite containing the Cocos 2d logo. At the end, it returns true to show it successfully initialized the HelloWorld object
    • Label — A string represented on the screen of your app
    • Sprite — An image
  • void HelloWorld::menuCloseCallback(cocos2d::Ref* pSender) — Closes the program
    • #if/#endif — Tells the preprocessor to only allow compilation of the lines that reduce to true

There you go! That’s everything you need to know about a basic Cocos 2d-x program. Let me know if it helped or if you still have any questions by posting them below.