Developers Manual > Cocos2d-x > Deprecated Docs for Cocos2d-x > Step by Step Cocos2dxSimpleGame Series > Chapter 2 - How to Add a sprite

Chapter 2 - How to Add a sprite

The source code of these tutorials is here: https://github.com/flyingpacer/Cocos2dxSimpleGame. You can follow the articles to finish the game by yourself step by step, or download the finally source, simply build and run it.

1. Add image resources

Here’re three images made by Ray Wenderlich ’s wife , which would be used in Cocos2dSimpleGame.

After Chapter 1 - Create a New cocos2d-x project with multi-platforms, you must have cocos2d-x/Cocos2dSimpleGame folder now. Please download these images and copy them to cocos2d-x/Cocos2dSimpleGame/Resources folder

Then return to the IDE of different platforms.

1.1 add resources on iphone

It’s so easy, open Xcode and click Add -> Existing Files from the context menu of Cocos2dSimpleGame/Resources group, add these three images above.
Notice that you should tick the check box of Cocos2dxSimpleGame in the “Add to Targets” form

1.2 add resources on android

If you run build_native.sh for compilation, you should copy the images to the Resources folder, else you should copy the image files to “assets” folder.

1.3 add resources on win32

Win32 executable files will find the resources from it’s relative path. So we had to copy the images from cocos2d-x/Cocos2dSimpleGame/Resources folder to cocos2d-x/Debug.win32 folder manually.
But lazy guys like me, can always find lazy ways.

Write this line into Post-Build Event-> Command Line

xcopy /Y /E .\Resources\*.* $(OutDir)

Each time the building completed, VistualStudio will copy the resources to the executable path

2. Add a sprite

You can see how easy to port cocos2d games from objc to c*+ now. Open HelloWorldScene.cpp, replace the init method with following.

bool HelloWorld::init(){     bool bRet = false; do
    {
        //////////////////////////////////////////////////////////////////////////
        // super init first
        //////////////////////////////////////////////////////////////////////////      CC_BREAK_IF(! CCLayer::init());
        //////////////////////////////////////////////////////////////////////////
        // add your codes below...
        //////////////////////////////////////////////////////////////////////////
        // 1. Add a menu item with "X" image, which is clicked to quit the program.
        // Create a "close" menu item with close icon, it's an auto release object.
        CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
        "CloseNormal.png",
        "CloseSelected.png",
        this,
        menu_selector(HelloWorld::menuCloseCallback));
        CC_BREAK_IF(! pCloseItem);
        // Place the menu item bottom-right conner.
        pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
        // Create a menu with the "close" menu item, it's an auto release object.
        CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
        pMenu->setPosition(CCPointZero);
        CC_BREAK_IF(! pMenu);    
        // Add the menu to HelloWorld layer as a child layer.
        this->addChild(pMenu, 1);
        /////////////////////////////
        // 2. add your codes below...
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        CCSprite *player = CCSprite::create("Player.png",
        CCRectMake(0, 0, 27, 40) );
        player->setPosition( ccp(player->getContentSize().width/2, winSize.height/2) );
        this->addChild(player);
        bRet = true;
    } while (0);
    return bRet;
}

Beyonds the close menu, we only add the section of “2. Add your codes below” actually. You can see how to translate cocos2d-iphone codes line by line simply to cocos2d-x multi-platform codes.

// cpp with cocos2d-x
bool HelloWorld::init()
{
    if ( CCLayer::init() )
    {
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        CCSprite *player = CCSprite::create("Player.png", 
                                     CCRectMake(0, 0, 27, 40) );
        player->setPosition( ccp(player->getContentSize().width/2, 
                              winSize.height/2) );
        this->addChild(player);
    }
    return true;
}

TIPS 1

# Don’t use**__super* in C*+ like used in objc. The keyworkd __super is only recognized by VC**, but can not be compiled by GCC. So you better to call the name of parent class, CCLayer::init
# There’s no the concept of property as there is in objc. Use get/set methods instead. For example, if you want to fetch the contentSize property of CCSprite , you must call sprite->getContentSize method. Make the first letter capital, then add “get” prefix to it.
# Use setter to set the value of properties. So “player.position = …” , translates to player->setPosition
# But the access to members of structures isn’t following this rule. E.g. there’re no getter/setter wrapper with the “width” & “height” in winSize structure.
# We have implemented some frequently used functions of CGGeometry, such as CGRectMake, CGPointMake, CGSizeMake, CGPointZero, CGSizeZero, CGRectZero. You can find them in cocos2dx/include/CCGeometry.h. Their features are same as iOS. For naming conflicts, classes with CG, NS, UI prefix, has been changed to CC prefix in cocos2d-x.
# All the gaming elements in cocos2d-x, such as sprite, layer, scene, label, action, are allocated in the heap. So we must call their methods by “->”
# Use keyword “this” in cpp instead of “self” used in objc.
# The return type of init method is “bool” now. There’s no keyword “id” in cpp, so the methods returning “id” is translated to a object pointer or bool.
# For android, the title bar has ocupied some space, so you should set the player’s position to ccp.
Well, we can build and run the code. Now the ninja is dressed in black, hidden in the black background with red eyes. For the gameplay, we had to change the background to white. It’s so easy, modify HelloWorld to inherit from CCLayerColor instead of CCLayer.
At first, modify the declaration in HelloWorldScene.h

// cpp with cocos2d-x
class HelloWorld : public cocos2d::CCLayerColor

Then modify the very beginning of HelloWorld::init from

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

to

if ( !CCLayerColor::initWithColor( ccc4(255,255,255,255) ) )
{
    return false;
}

Here’s a bit different to RayWenderlich’s code, because prefer defensive programming. The normal code is if supoer init success, then do bla-bla…, I prefer if init failed, do the error handling first, then continue writing the correct flow. OK, back to the topic. Let’s compare the translation of objc to cpp again

// cpp with cocos2d-x
if ( CCLayerColor::initWithColor( ccc4(255,255,255,255) ) )

TIP 2

# The default permission of inheritance in c** is private. So the modifier “public” before CCLayerColor is required.
# RicardoQuesada, the chief author of cocos2d-iphone , suggest us to use namespace in cocos2d-x. It’s very important to check your invoking of cocos2d-x classes is in “cocos2d” namespace or in “CocosDenshion” namespace

Build and run, then you can see the hero standing lonely in the white background.

  • IPhone
  • Android
  • Win32

Player.png (4.2 kB) walzer, 2010-12-28 01:58

Projectile.png (4.5 kB) walzer, 2010-12-28 01:58

Target.png (5.1 kB) walzer, 2010-12-28 01:58

img-2-1.3-xcopy.png (49.9 kB) walzer, 2010-12-28 01:58

img-2-2.0-iphone.png (104.8 kB) walzer, 2010-12-29 23:20

img-2-2.0-uphone.png (79 kB) walzer, 2010-12-29 23:20

img-2-2.0-win32.png (15.6 kB) walzer, 2010-12-29 23:20

Win32Sprite.png (15.7 kB) huangrh, 2011-03-18 00:40

androidSprite.png (67.2 kB) huangrh, 2011-03-19 02:27

IOSAddResource.png (78.7 kB) huangrh, 2011-03-20 23:07

IOSSprite.png (118.1 kB) huangrh, 2011-03-20 23:07

IOSAddResource.png (78.2 kB) huangrh, 2011-09-28 23:38

Copyright © 2010 - 2013 Cocos2d-x.orgClustrmaps