Cocos2D-X Tutorial for iOS and Android: Space Game

In this Cocos2D-X tutorial, you will learn how to build a space game similar to the one was built in the How to Make a Space Shooter iPhone Game. There will be one major difference – this will be written in beautiful cross-platform C++, using Cocos2D-X! By .

Leave a rating/review
Save for later
Share

Update 5/14/2013: Fully updated for Cocos2D-X 2.1 and iOS 6. (original post by Jean-Yves Mengant, update by Jorge Jordán).

Update 5/4/2014: You can find the code for this tutorial updated to Cocos2D-X 3.0 by @pahakorolev here.

In this Cocos2D-X tutorial, I will show you how to build a space game similar to the one was built in the How to Make a Space Shooter iPhone Game.

There will be one major difference – this will be written in beautiful cross-platform C++, using Cocos2D-X!

This means you’ll be able to run this game on both your iPhone and Android by the end of this Cocos2D-X tutorial. And with a little more work, you could get it running on other platforms as well – from Windows to Linux to the Mac!

This Cocos2D-X tutorial picks up where the Cocos2D-X Tutorial for iOS and Android: Getting Started left off. So if you haven’t already, read that project first and get your project set up the way described there.

So put on your Star Wars CD to set the mood, and let’s get started!

Getting Started

First things first – go ahead and download the space game resources ZIP file and unzip them to your hard drive.

You want to add these in a way so the same files can be used in both the Android and iOS projects, much like you did for the reusable C++ classes. To do this, you’ll add the files to the Android project’s Resources directory, and add relative links to this directory from your iOS project.

To add images and other resources into your project, you need to add them into $PROJECT_HOME\Resources (Remember that $PROJECT_HOME is the location of your Android Cocos2D-X project – samplecocos2dxandroid). (But don’t copy them yet – there’s a trick I’ll tell you about soon).

However, there’s one problem with this plan: the Eclipse project will only show files inside $PROJECT_HOME\android.

Luckily there is an easy workaround: you’ll make a link from $PROJECT_HOME\proj.android\Resources to $PROJECT_HOME\Resources – this way the files are where they need to be, but Eclipse can see them.

To do this, open up a Terminal and run the following command from within the $PROJECT_HOME\proj.android folder:

ln -s ../Resources ./Resources

If you go back to Eclipse, right click the project, and select Refresh, you should see the new folder Resources appear.

Now it’s time to copy the files to the $PROJECT_HOME\Resources folder, but let me tell you the trick I mentioned earlier.

For cross platform portability reasons, you should avoid using subdirectory hierarchies inside the $PROJECT_HOME\Resources folder. Although subdirectories work fine under iOS, they do not work well on Android. For example, if you had the Sprites.pvr.ccz file inside a SpriteSheet subdirectory, on Android the CCSpriteBatchNode::batchNodeWithFile Cocos2DX method would fail and return a null pointer.

So copy all of the individual files from the space game resources ZIP file into the $PROJECT_HOME\Resources folder. Remember not to create any subdirectories, just copy the files over. There’s also an existing Fonts subfolder inside Resources, move all the files inside Fonts into $PROJECT_HOME\Resources as well.

Additionally, there’s a Classes subfolder inside the ZIP file that you should not add to the $PROJECT_HOME\Resources – just delete that folder, or keep it for later reference when you get to the point where those particular files are created in this Cocos2D-X tutorial. When you’re done your $PROJECT_HOME\Resources folder should look like this:

Adding-resources-to-a-Cocos2D-x-Project

Next, let’s bring in these same files in to the iOS project as well. Open your Xcode project, and create a new group called SharedResources. Select the new group, and in the File Inspector click the button next to Path and browse to your $PROJECT_HOME\Resources.

Browsing-to-the-Resources-folder

Then right click the SharedResources group, select Add Files, and add all of the files from the $PROJECT_HOME\Resources folder. Make sure that the Copy items into destination group’s forder checkbox is not checked before you click Add. w00t – you’re fully set up!

Adding A Space Ship

Let’s try this out and see if it works! In your Eclipse project, open up Classes\HelloWorldScene.h and add the following to the beginning of the HelloWorldScene class (above the existing public: line):

private:
	cocos2d::CCSpriteBatchNode * _batchNode;
	cocos2d::CCSprite * _ship;

This creates two private instance variables – one for the sprite batch node, and one for the space ship sprite.

Next switch to HelloWorldScene.cpp and, inside the init() method, delete everything from the comment 2. add a menu item to the end of the method. Then add the following:

_batchNode = CCSpriteBatchNode::create("Sprites.pvr.ccz");
this->addChild(_batchNode);
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Sprites.plist");

_ship = CCSprite::createWithSpriteFrameName("SpaceFlier_sm_1.png");
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
_ship->setPosition(ccp(winSize.width * 0.1, winSize.height * 0.5));    
_batchNode->addChild(_ship, 1);
return true;

Note that this code looks very similar to what you’re used to with Cocos2D in Objective-C. The API is pretty much the same, it’s just that there’s some differences in C++ language syntax.

Compile and Run in your Android simulator, and you should see your ship appear on the screen:

Space-Flier-Android

And the best part is it works on iOS as well!

Space-Flier-Xcode

Adding Parallax Scrolling

Next, let’s add the space background and make it scroll in a cool way with parallax scrolling.

First, it’s annoying to have to prefix everything with the cocos2d namespace, so add this line to HelloWorldScene.h, right before the class declaration:

USING_NS_CC;

Then add some new variables to the private section of the HelloWorldScene.h file (note you don’t need to prefix them anymore):

CCParallaxNode *_backgroundNode;  
CCSprite *_spacedust1;
CCSprite *_spacedust2;
CCSprite *_planetsunrise;
CCSprite *_galaxy;
CCSprite *_spacialanomaly;
CCSprite *_spacialanomaly2;

Next, add the following to the HelloWorldScene.cpp‘s init() method, right before the return statement:

// 1) Create the CCParallaxNode
    _backgroundNode = CCParallaxNode::create(); //1
    this->addChild(_backgroundNode,-1);
    
    // 2) Create the sprites will be added to the CCParallaxNode
    _spacedust1 = CCSprite::create("bg_front_spacedust.png");
    _spacedust2 = CCSprite::create("bg_front_spacedust.png");
    _planetsunrise = CCSprite::create("bg_planetsunrise.png");
    _galaxy = CCSprite::create("bg_galaxy.png");
    _spacialanomaly = CCSprite::create("bg_spacialanomaly.png");
    _spacialanomaly2 = CCSprite::create("bg_spacialanomaly2.png");
    
    // 3) Determine relative movement speeds for space dust and background
    CCPoint dustSpeed = ccp(0.1, 0.1);
    CCPoint bgSpeed = ccp(0.05, 0.05);
    
    // 4) Add children to CCParallaxNode
    _backgroundNode->addChild(_spacedust1, 0, dustSpeed, ccp(0,winSize.height/2) ); // 2
    _backgroundNode->addChild(_spacedust2, 0, dustSpeed, ccp( _spacedust1->getContentSize().width,winSize.height/2));
    _backgroundNode->addChild(_galaxy, -1, bgSpeed, ccp(0, winSize.height * 0.7));
    _backgroundNode->addChild(_planetsunrise, -1 , bgSpeed, ccp(600, winSize.height * 0));
    _backgroundNode->addChild(_spacialanomaly, -1, bgSpeed, ccp(900, winSize.height * 0.3));
    _backgroundNode->addChild(_spacialanomaly2, -1, bgSpeed, ccp(1500, winSize.height * 0.9));

Again, this is quite similar to the code in the Cocos2D space shooter tutorial, there are only minor syntax changes. You might enjoy comparing the two tutorials to see the differences in syntax.

Compile and Run in your Android simulator, and you should see the start of a space scene:

Space-Flier-Parallax-Android

And again, it works on the iPhone too!

Space-Flier-Parallax-Xcode

Now it’s time to make the background scroll. First, predeclare the update method in HelloWorldScene.h – you can add the following code to either the private or public section but since the update method is used internally, it’s probably more appropriate to add it as a private method:

// scheduled Update 
void update(float dt);

Then add the implementation at the end of HelloWorldScene.cpp:

void HelloWorld::update(float dt) {
  CCPoint backgroundScrollVert = ccp(-1000, 0);
  _backgroundNode->setPosition(ccpAdd(_backgroundNode->getPosition(), ccpMult(backgroundScrollVert, dt)));
}

Finally, call the scheduleUpdate method at the end of the init() method (but before the final return statement):

this->scheduleUpdate();   

Compile and Run, and you will see the background scroll!