Home Game Development Learning Cocos2d-x Game Development

Learning Cocos2d-x Game Development

By Siddharth Shekar
books-svg-icon Book
eBook $28.99
Print $48.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99
Print $48.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started
About this book
Publication date:
September 2014
Publisher
Packt
Pages
266
ISBN
9781783988266

 

Chapter 1. Getting Started

In this chapter, we will look at the basics of the Cocos2d-x frameworks and get the required tools installed to create the Cocos2d-x project. This will include downloading and installing Visual Studio IDE, Windows Phone SDK, Python, and Cocos2d-x and creating the project. We will also cover some basics such as coordinate systems, fundamental classes of Cocos2d-x, and how to run the same project on different devices running on different platforms.

The topics you will learn in this chapter are as follows:

  • Downloading and installing Visual Studio

  • Downloading and installing Windows Phone SDK

  • Downloading, installing, and configuring Python

  • Downloading Cocos2d-x

  • Creating your project and running it on a simulator

  • The basics of Cocos2d-x, the coordinate system, and project structure

  • Running the project on multiple platforms

The following are the requirements to get started:

  • Windows 8.0 (64-bit)

  • Visual Studio 2012 Express Edition

  • Windows Phone SDK 8.0

  • Python Version 2.7.6

  • Cocos2d-x Version 2.2.3

At the time of writing this book, Version 3.0 of Cocos2d-x had already been released. I am using Version 2.2.3 for this book for the following reasons:

  • Version 2.2.3 supports a wide array of platforms such as Blackberry, Windows Phone, Tizen, and Marmalade

  • There are a lot of tools that are freely available for Version 2.2.3 for advertisements, in-app purchases, and leaderboard and achievement integration, which in v3.0 you would have to write yourself at the moment

That being said, I would definitely keep a watch on v3.0 and the platforms it supports in the future releases. Also, the tools are being updated to support Version 3.0. I would recommend downloading v3.0 from the site and practicing with it once you have a good understanding of how Cocos2d-x works.

Note

If you wish to run the game on iOS, Android, or Blackberry instead of Windows Phone 8, you can refer to Chapter 11, Porting, References, and Final Remarks, and see how to configure the IDE for that OS and then continue from the next chapter.

For Win32, you can continue with this chapter and you wouldn't have to install Windows Phone 8 SDK. You can also run the project on Windows 7 or higher machines, but you will have to make a small change in the AppDelegate.cpp file, which is mentioned in Chapter 11, Porting, References, and Final Remarks.

Also, while opening the win32 project developed in Visual Studio 2012 with the currently installed Visual Studio 2013, you might get some errors. The following are the steps to be taken to fix this:

  1. Right-click on the wp8GameComponent project and then click on Properties.

  2. In General under Configuration Properties, make sure Windows Phone 8.0 (V110) is selected for Platform Toolset.

    Note

    Cocos2d-x 2.2.3 can be downloaded for all the OSes from the links in this chapter.

 

Downloading and installing Visual Studio


For this book, I will be using Visual Studio 2012 Express Edition. It can be downloaded from the Microsoft Download Center at http://www.microsoft.com/en-gb/download/details.aspx?id=34673. The following are the steps to download and install Visual Studio:

  1. Click on Download, as shown in the following screenshot, and select VS2012_WDX_ENU.iso:

  2. Click on Next and your download should begin.

  3. Once downloading is complete, double-click on the ISO file; Windows will mount it as a disk drive. Double-click on winexpress_full.exe. This should start the installation of Visual Studio.

  4. Once installed, move on to the next step in which we will be installing the Windows Phone SDK.

 

Downloading and installing the Windows Phone SDK


To test the game on the simulator or device, you will need the Windows Phone SDK. This can be downloaded from http://dev.windowsphone.com/en-us/downloadSDK.

Once you go to this link, under SDK 8.0, click on the Download button, as shown in the following screenshot. This will download WPexpress_full.exe.

Double-clicking on Install will initiate the installation of the SDK and install it on the machine. If Hyper-V is turned off, after restart, go to the system BIOS and enable virtualization to enable Hyper-V.

Hyper-V is a virtualization tool that enables you to run the Windows Phone 8 simulator on your PC. Like any virtualization tool, it will use some part of your current system resources such as hard disk, processor, and RAM and show you how the game/application will run on the device. But since it uses your current system resources, it is like running one system inside another system, so the result won't be exact, as it would be on the device, but at least it will give a good idea of how the application/game will look on the device. For actual testing, I still would recommend using an actual device.

 

Downloading and installing Python


You can skip this section if you want to create a Cocos2d-x project on Mac as Python is preinstalled in OS X, which we will cover in Chapter 11, Porting, References, and Final Remarks. But for Windows, you will have to install and configure Python.

Download and install Python using the following steps:

  1. To download Python, go to http://www.python.org/download/ and click on Python 2.7.6 Windows x86-64 Installer.

  2. Once downloaded, double-click on the EXE file to start the installation. Once installed, you will see a Python27 folder in your C: drive.

  3. Next, you will have to configure Python. Right-click on Computer and select Properties, as shown in the following screenshot. This will open the System panel.

  4. On the System panel, click on the Advanced system settings link on the left-hand side.

  5. Now click on the Advanced tab and then click on Environment Variables....

  6. Under user variables for [user's account name], click on New.... In Variable name, type in PATH and in Variable value, type in the path c:\Python27;c:\Python27\Lib\site-packages\;c:\Python27\Scripts, as shown in the following screenshot:

  7. Click on OK and close the System panel. To check whether Python was configured correctly, press Windows + R, type in cmd in the Open textbox of the Run command box, and then click on OK. This will open the command prompt window.

  8. In the command prompt, type in python. This should display the version of Python installed. In this case, it is 2.7.6. Refer to the following screenshot:

If you see the preceding window, Python is configured correctly. If not, check whether you have followed the steps correctly and haven't missed anything. Also make sure that the command is typed exactly as given in step 8. Once Python is installed and configured, we can move to the next step, which is downloading Cocos2d-x.

 

Downloading Cocos2d-x


Download Cocos2d-x using the following steps:

  1. To download Cocos2d-x, go to http://www.Cocos2d-x.org/download and download Version 2.2.3 from the website.

  2. Once downloaded, you can unzip the Cocos2d-x-2.2.3 folder to any folder on the system; I am extracting it onto the desktop.

  3. Make sure you are downloading the Cocos2d-x version and not the JS or HTML5 version of Cocos2d.

  4. Once downloaded, unzip the folder. With Cocos2d-x downloaded and extracted, we can now create a new project.

 

Creating a new project


Use the following steps to create the project:

  1. Press Windows + R and type in cmd.

  2. On the command prompt, type in the following command and press Enter:

    cd desktop\coco2d-x-2.2.3\tools\project-creator
    
  3. In the project-creator folder, type in the following command and press Enter:

    python ./create_project.py –project wp8Game –package com.testpackage.wp8Game –language cpp
    

    You will be presented with the screen shown in the following screenshot:

    Note

    Once the project is created in the project folder, you shouldn't move the folder around as it will lose the references to Cocos2d-x and the folder required to run the game.

  4. Now navigate to the project's folder in Cocos2d-x-2.2.3. You will find the new folder created, named wp8Game. Double-click on it and you will see the folder structure, shown as follows:

    You can see a Classes folder, a Resources folder, and project folders for all the different platforms that Cocos2d-x supports.

  5. Since we are making a game for the Windows Phone platform, double-click on the proj.wp8-xaml project folder and double-click on wp8Game.sln.

  6. When asked for application preference, choose the Windows Phone option. This will open the project in Visual Studio, as shown in the following screenshot:

  7. To run the project on the emulator, select Emulator WVGA 512MB and click on the green play button. This will take some time to build; once built, the project should run on the simulator, as shown in the following screenshot:

Congratulations on creating a new project! Now that the project is created, let's take some time to understand the fundamentals of the coordinate system and the basic classes used in Cocos2d-x that serve as the building blocks for creating any game.

 

Coordinate system


Coordinate systems are used to determine the position of the objects on the screen. Cocos2d-x uses a rectangular coordinate system with the bottom-left corner of the screen being the origin in landscape mode and top-left corner in portrait mode.

From the bottom-left corner of the screen, imagine a line going straight towards the bottom-right corner, which would be the x axis, and a line going up from the origin to the top-left corner, which would be the y axis. There is also a z axis that is coming out of the screen from the origin. This is irrespective of whether you are holding the device in the landscape or the portrait position. Refer to the following figure:

Since Cocos2d-x is the 2D game development framework, we will be mostly dealing with the x and y coordinates. The z axis is used mainly for placing objects in front or behind other objects. To decide which image is above another image, Cocos2d-x has something called a Z-order. The higher the Z-order, the further away from the screen that image will be.

A positive z value means that you are placing the object in front of other objects and a negative z value means that you are placing it behind other objects. For example, the background image would usually have a Z-order of 0 or -1. And you would place other objects at a value that is higher than that value since you would want the background to be behind all the other objects on the screen.

Also, if you don't specify the Z-order while adding a layer or sprite, the next available Z-order will be taken by default. For example, if you add a background sprite and then immediately add the player sprite, the player sprite will be drawn above the background and you will be able to see both the player and the background. If you add them the other way around, you won't be able to see the player as the background is at a higher Z-order than the player and hence the player will be drawn beneath the background and you will be able to see only the background. You might think the player is not drawn but in fact the player is being drawn but under the background, so you don't see it.

The distance is measured in pixels. So assume you have a Nokia 820, which has a screen resolution of 800 x 480 when viewing the screen in landscape mode, which means the width of the screen is 800 pixels and the height is 480 pixels. So if you wanted to place something on the middle of the screen, you would move 400 pixels from the right of the origin and then go up 240 pixels from the bottom of the screen to place the object at (400, 240).

 

Basic classes of Cocos2d-x


The following are the basic classes of Cocos2d-x:

  • CCScene: A CCScene class is used to make screens such as the menu screen, game screen, and credits screen. The CCScene class can be used as a container of CCLayers. It is an abstract entity and you can apply transitions on it to go between scenes such as the menu scene, gameplay scene, and options scene.

  • CCLayer: In a scene, you can have different layers to help you organize your scene better just like in Adobe Photoshop. In games, you would usually have different layers such as the Heads-up Display (HUD) and background. Also, CCLayers, unlike CCScenes, have the ability to receive touch and accelerator events. Inside CCLayers, you can have CCSprites, CCMenus, and so on.

  • CCSprite: This is the class that is used to display the images on the screen. The image could be in .png or .jpg format. It has various properties such as the width and height of the image, setPosition, setScale, and setRotation, which can be used to manipulate the image's position, scale, and rotation.

  • CCLabeITTF: This is used whenever you wish to display any text on the screen. It is mainly used for showing tutorials or level numbers at the start of the game. The text can also be dynamically changed, for example, while updating the score during the game. The user can apply styles, fonts, colors, sizes, and so on on a CCLabeITTF.

  • CCMenu: This is used for placing the UI elements in the game such as buttons. CCMenuItems are used to attach the images, position them, and then add them to CCMenu so that they are displayed on the screen. Although you can position the CCMenu, it is general practice to position CCMenuItems instead and keep CCMenu positioned at the origin.

The following is the Gameplay scene from my game, pizzapMania, which shows the layers in the Gameplay scene in action:

The Gameplay scene can be further divided into the background layer, with Z-order 0, which is a CCLayer containing the background image that is a CCSprite. The gameplay layer at Z-order 1 contains gameplay elements such as the player and houses that are all sprites. Finally, the HUD layer, at Z-order 3, has the pause button and controls that are sprites and score, time elapsed, and coins collected are CCLabeITTFs that are updated periodically.

If you don't understand what a Z-order is, go through the Coordinate system section to refresh your memory.

Here, I have included the controls in the HUD layer itself. You could create a new layer and add the controls to it so that it is handled separately on a separate layer. Refer to the following screenshot:

 

Project breakup


First, let's look at the structure of Solution Explorer:

In the Solution Explorer pane, we have the following projects:

  • Angle project: As Cocos2d-x uses the openGL ES 2.0 graphics library and Windows uses DirectX to display objects on the screen, the Angle project converts all the openGL ES code to DirectX. For more information on Angle projects, you can visit the MSOpenTech GitHub page at https://github.com/MSOpenTech/angle.

  • CocosDenshion: This is the audio library. Whenever we want to play a sound or an effect, we would make use of this project for the audio to play properly. We will be looking into it when we include music and sound effects in the game.

  • libbox2d: This is a physics framework that can be used to make complex physics-based games. It is written by Erin Catto and it is used by most of the popular 2D physics-based games such as Angry Birds and Cut the Rope, to name a few. You can learn more about Box2D at http://box2d.org.

  • libChipmunk: Similar to Box2d, Chipmunk is also a physics framework that can be used to make physics simulation in your games to make it more realistic and fun. You could either use Box2d or Chipmunk depending on your comfort level. More can be learned at https://chipmunk-physics.net.

  • libExtensions: This contains some third-party plugins and helper projects that you can use out of the box in Cocos2d-x. For example, Spine is a 2D skeletal animation toolkit that can used to make 2D animations in Cocos2d-x, and CocosStudio is used to make UI, animations, and scenes using this simple tool. You can learn more about Spine at http://esotericsoftware.com/ and CocosStudio at http://www.Cocos2d-x.org/wiki/CocoStudio.

These are the projects that will be included by default in all the projects that you create. The next two projects are the ones that are created depending on what name you gave to the project.

In this case, there is the wp8Game project and the wp8GameComponent project. If you look at other Windows projects such as proj.win32, proj.winrt, or proj.wp8, there will only be one project with the project name. So why are there two projects here?

The short answer is that, in order to integrate ads and in-app purchases into the game, we would need to create an XAML project. If your game doesn't have in-app purchases or ads, you can use the proj.wp8 project instead of proj.wp8-XAML.

You will see that the wp8Game project has a C# in front of it and wp8GameComponent has a ++ sign in front of it in Visual Studio's Solution Explorer. All of the game logic would be written in the component project in C++, which while running will talk to the C# layer and call the ads and in-app purchases in C# when required.

Until we start integrating the ads and in-app purchases, we will mainly be typing in the code in C++ in the component project. But make sure that the wp8Game project is set as the current project by right-clicking on the project and selecting the appropriate option.

Let's look into the classes that actually participate in starting the app and displaying the objects on the screen. We will look into the wp8Game project later, but for now let's expand the wp8GameComponent project.

There are a bunch of dependencies, other renderers, input classes, and the classes folder. In this classes folder, you will find the following three classes:

  • AppDelegate

  • HelloWorldScene

  • AppMacros

Let's look at these in detail.

AppDelegate is the class that is responsible for initiating the application and getting it ready to display the game/application on the screen of the device or on the simulator. If you open up the AppDelegate.cpp file, you will find the following functions:

  • applicationDidFinishLaunching

  • applicationDidEnterBackground

  • applicationWillEnterForeGround

Let's look at these functions in detail.

The applicationDidFinishLaunching function is called when the application is launched. In applicationDidFinishLaunching, there are two variables, CCDirector and CCEGLView. Both the classes are singleton, meaning that only one instance of each is created for this project and that instance is shared when required. Also, it can be accessed from any class at any time, provided the correct header files are used.

CCDirector is a very important class; it keeps a track of which scene is currently loaded and takes care of opening a new scene and replacing the current scene with another scene. Here, we get the shared instance of CCDirector:

CCDirector* pDirector = CCDirector::sharedDirector();

Note

We will go through scenes in a little more depth later in the chapter.

CCEGLView takes care of checking the resolution of the current device this application is running on and creates a view so that objects can be displayed on the screen. Similar to CCDirector, we get the shared instance of it:

CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();

The director also needs to be aware of the view variable, so the newly created view is given to it:

pDirector->setOpenGLView(pEGLView);

Next, the director is told whether we want the frames per second to be displayed on the screen:

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

The fps is always displayed at the bottom-left corner of the screen. If we wish to disable it, we can set true to false. In fact, once the game is done and you are ready to release it, make sure that you set it to false.

Next, the animation interval is set. Here, the CCDirector class is told how often the update function should be called:

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

The animation interval is set to 1.0 / 60. So right now, it is set at 60 frames per second. So the game is updated 60 times in a second. So each frame is called approximately every 0.0167 seconds.

Now we take the HelloWorld scene and make the application run with the scene by telling the director to start the application with this scene:

// create a scene. it's an autorelease object
CCScene *pScene = HelloWorld::scene();

// run
pDirector->runWithScene(pScene);

The applicationDidEnterBackground function tells CCDirector that the application has gone into the background, so the animations and sounds of the game should be stopped. This is the function that is responsible for pausing your game when you get a call while playing a game.

The applicationWillEnterForeGround function is similar to applicationDidEnterBackground. The applicationWillEnterForeGround function will tell the director to start the animations and sounds as the application is coming to the foreground.

That is all for the AppDelegate class. Next, we will move on to the HelloWordScene class, where most of the game logic will be written. In HelloWorldScene.h, you will see that it starts with #include cocos2d.h, which is the Cocos2d header. It needs to be included in all the classes that you create if you need access to Cocos2d functions and properties.

In the interface, you will see that the name of the class is HelloWorld and it inherits from CCLayer:

class HelloWorld : public cocos2d::CCLayer

The virtual bool init() function is the first function that is called to initiate the layer. So, this is where you will be initializing the variables and the settings for the game.

In static cocos2d::CCScene* scene(), a new scene is created and the HelloWorld layer is attached to the scene and the function is returned.

The void menuCloseCallback(CCObject* pSender) statement is a callback function that is called when you press the close button on the screen. However, this doesn't work in Windows Phone. But, if you are running this project on an iOS or an Android device, this function will close the application and return to the home screen.

CREATE_FUNC(HelloWorld) is a macro that creates and initializes the HelloWorld class by calling its constructor and calling the init function. We will be creating our own custom create function when we create the enemy class later so that you can see what a create function looks like.

Let's move forward and open up the HelloWorldScene.cpp file. This file includes the HelloWorldScene.h file and uses a USING_NS_CC macro to set the namespace to Cocos2d. You could use using namespace cocos2d; but USING_NS_CC is a macro that includes CCPlatformMacros.h, which itself has a lot of predefined macros in it, so you might have to include it separately if required. But for this book, either can be used:

#include "HelloWorldScene.h"

USING_NS_CC;

Next is the definition for the scene function that returns the current scene after adding the current layer, which is the HelloWorld layer:

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();

    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

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

    // return the scene
    return scene;
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The scene and layer are autorelease instances, meaning that you don't have to delete these pointers manually and release them as they are part of a release pool and will be released automatically.

Next is the init() function, in which you call the init() function of the super class:

if ( !CCLayer::init() )
{
  return false;
}

Then there are two variables, visibleSize and origin, of type CCSize and CCPoint respectively. CCSize is a class with two floats—width and height. You can perform functions such as setting the width and height and you can also check whether two CCSizes are equal. CCPoint is a class with two floats, x and y, which are used to define a point in 2D space. You can also do additional operations such as checking the distance between two CCPoints, get the dot or cross products, and get the angle between the two points.

The visibleSize variable stores the current resolution of the screen and origin stores the origin of the current scene. Both are retrieved from the CCDirector singleton class:

CCSize visibleSize =
  CCDirector::sharedDirector()->getVisibleSize();

CCPoint origin =
  CCDirector::sharedDirector()->getVisibleOrigin();

The origin is always set at the bottom-left corner of the screen by default in landscape and top-left corner in portrait with the right being the positive x direction and up being the positive y direction. This is valid whether you are in landscape mode or portrait mode irrespective of what device you are running or building the game on.

After getting the screen resolution and the origin of the current layer, we can start placing our object onto the layer.

First, the close button is created that will call the menuCloseCallBack function when clicked, causing the application to shut down. For this, an instance of CCMenuItemImage is created, called pCloseItem. It takes four parameters:

  • The image that is shown when the button is not clicked

  • Which image should replace the original once the button is clicked

  • The target class, which in this case is the current class

  • What function should be called when the button is clicked, so in this case, we call the menuCloseCallBack function

Refer to the following code snippet:

CCMenuItemImage *pCloseItem = CCMenuItemImage::
create("CloseNormal.png",
       "CloseSelected.png",
       this,
       menu_selector(HelloWorld::menuCloseCallback));

Next we set the position of the menu item image and place it at the bottom-right corner of the screen. This is done by taking the screen's width, subtracting half of the button's width, and then placing it at half of the button's height above the bottom of the screen. Both the button's height and width are divided by two as the anchor points for the image are at the center of the image:

pCloseItem->setPosition(ccp(
origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
origin.y + pCloseItem->getContentSize().height/2));

Next, for the menu button to be displayed on the screen, the menu button image needs to be added to CCMenu. So, we create an instance of the CCMenu class and add pCloseItem into it. We have to include NULL at the end to tell CCMenu that there are no more items to be added. The position is set to the bottom-left corner by setting the position to CCPointZero. Finally, it is added to this layer's display list with a Z value of 1:

CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 1);

To display the "Hello World" text on the screen, CCLabeITTF is used. A new instance of it is created, called pLabel, and it takes three default values, which are:

  • What text you want to display; this should be within double quotes

  • The name of the font; this should be in double quotes

  • The size of the font

Refer to the following code:

CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);

Then the position is set by setting the x position in the middle of the screen and the y position at the height of the screen and subtracting the height of the content size's text from it. Refer to the following code for more clarity:

pLabel->setPosition(ccp(
origin.x + visibleSize.width/2,
origin.y + visibleSize.height - pLabel->getContentSize().height));

Then the label is added to the display list using the addchild function and keeping the z depth 1:

this->addChild(pLabel, 1);

And finally, to display the background image, a CCSprite variable is created called hero and it is given the name and extension of the image to be displayed, in quotes:

CCSprite* hero = CCSprite::create("HelloWorld.png");

Next, its position is set at the center of the screen:

hero->setPosition(ccp(
visibleSize.width/2 + origin.x,
visibleSize.height/2 + origin.y));

Finally, it is added to the display list with z depth as 0:

this->addChild(hero, 0);

The z depth is kept at zero so that it is behind all the objects that would be created.

The AppMacros.h file is used for resource management to handle different screens. We will go in detail later in the book when we make the game compatible with different screen resolutions.

 

Running the project on multiple platforms


The same project can be run on different platforms. Let's see a few examples of the same project, running on Windows (desktop mode), Windows RT (tile mode), iOS, and Android with ease and with no need to rewrite the code for different languages.

Running the project on Windows (desktop mode)

To run the project on Windows desktop, go to the project's folder and open the proj.win32 folder and double-click on wp8Game.sln in desktop mode.

Once Visual Studio opens, click on Local Machine to build and run the project. Once built, you should see it running:

Running the project on Windows RT (tile mode)

To run the project in Windows RT mode, you will need the Visual Studio 2012 Professional or Ultimate edition. The following steps will help you run the project on Windows RT:

  1. In the project's folder, instead of proj.win32, open proj.winrt.

  2. Double-click on wp8Game.sln to open it in Visual Studio 2012.

  3. Select Local Windows Debugger in the drop-down list next to the green triangle button on the toolbar and click on it.

  4. Once it has been built, it will open in fullscreen mode, as shown in the following screenshot:

Running the project on the iPhone simulator using Xcode

You can even take a copy of the Cocos2d-x 2.2.3 folder to a Mac and run it on the simulator. Just install the Xcode IDE; go to the proj.ios folder and double-click on the Xcode project and that's all! You should now see the project running on an iOS simulator:

Running the project on an Android simulator using Eclipse

Running the project on Eclipse on an Android simulator is a long process, so I am just showing you the output on the Android Virtual Device (AVD):

Later in the book, we will also see how to configure the IDEs to run the project on an iOS simulator on Mac using the Xcode IDE and on Android simulator using the Eclipse IDE.

 

Summary


In this chapter, we learned how to install Visual Studio and the Windows Phone SDK. We downloaded Cocos2d-x 2.2.3 and created a new multiplatform project. We opened the project in Visual Studio 2012 and ran the project on the simulator.

We went through each of the projects in the Solution Explorer pane and understood what each of the projects do. We understood the fundamentals of the coordinate system and the basic classes in Cocos2d-x that are used to make any kind of game.

We then dug deeper to understand the different classes such as AppDelegate and HelloWorldScene, which are responsible for running the game. We also had a closer look at the individual functions and variables that are used to create, position, and display the objects on the screen.

If you wish, you can play around with the sprites by changing the position, rotation, and scale of the sprites to practice what you have learned so far. If you wish to know more about a class or a function, you can always press F12 and it will take you to the source file so that you can study it to get a deeper understanding of the implementation of the class. Don't be afraid to experiment. If you did something and don't know how to get back, you can always delete the wp8Game folder in the project and create a new project. Use this time to become familiar with Cocos2d-x and Visual Studio.

In the next chapter, we will start creating a game in which we will add the hero on the screen and make him move around using different control mechanics.

About the Author
  • Siddharth Shekar

    Siddharth Shekar is a game developer and teacher with over 6 years' industry experience and 12 years' experience in C++ and other programming languages. He is adept at graphics libraries such as OpenGL and Vulkan, and game engines such as Unity and Unreal. He has published games on the iOS and Android app stores. He has also authored books including Swift Game Development, Mastering Android Game Development with Unity, and Learning iOS 8 Game Development Using Swift, all published by Packt Publishing. He currently lives in Auckland, New Zealand, and is a lecturer in the games department at Media Design School. He teaches advanced computer graphics programming, PlayStation 4 native game development, and mentors final year production students.

    Browse publications by this author
Learning Cocos2d-x Game Development
Unlock this book and the full library FREE for 7 days
Start now