Cocos2d-x: Version 3.x Example code snippets


Scale the background image to fill the Screen


// ask the director for the visible window size
// specifically, it return visible size of the OpenGL view in points
Size visibleSize = Director::getInstance()->getVisibleSize();
    
// returns visible origin of the OpenGL view in points.
Point origin = Director::getInstance()->getVisibleOrigin();


// create background image from png
Sprite *bgImage = Sprite::create("HelloWorld.png");

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

// add background image at z-position = -1, bottom of all
// the z-position value is relative to parent
this->addChild(bgImage, -1);
    
// calculate the scaling factor to fill the screen size
float rX = visibleSize.width / bgImage->getContentSize().width;
float rY = visibleSize.height / bgImage->getContentSize().height;
    
// set the scaling factor to the background image
bgImage->setScaleX(rX);
bgImage->setScaleY(rY);

Add a close button to exit the application


// Step 1: Create and Add the button 

auto closeItem = MenuItemImage::create("CloseNormal.png",
                                       "CloseSelected.png",
                                       CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
    
closeItem->setPosition(Point(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(Point::ZERO);
this->addChild(menu, 1);


// Step 2: Button click handler / listener 

// menu close callback method 
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
}

Touch Detection (Touch Began, Touch Moved, Touch Ended)

HelloWorldScene.h


using namespace cocos2d;
using namespace std;

public:
    void onTouchesBegan (const vector<Touch *> &touches, Event *event);
    void onTouchesEnded (const vector<Touch *> &touches, Event *event);
    void onTouchesMoved (const vector<Touch *> &touches, Event *event);

HelloWorldScene.cpp


bool HelloWorld::init()
{
    // Enable touches 
    auto touchListener = EventListenerTouchAllAtOnce::create();
    touchListener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
    touchListener->onTouchesMoved = CC_CALLBACK_2(HelloWorld::onTouchesMoved, this);
    touchListener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
}

void HelloWorld::onTouchesBegan (const vector<Touch *> &touches, Event *event)
{
    CCLOG("onTouchesBegan called");
}

void HelloWorld::onTouchesEnded (const vector<Touch *> &touches, Event *event)
{
    CCLOG("onTouchesEnded called");
}

void HelloWorld::onTouchesMoved (const vector<Touch *> &touches, Event *event)
{
    CCLOG("onTouchMoved called");
}

Create a Sprite to the touch Location

follow the Touch Detection (Touch Began, Touch Moved, Touch Ended)

HelloWorldScene.cpp


void HelloWorld::onTouchesBegan (const vector<Touch *> &touches, Event *event)
{
    CCLOG("onTouchesBegan called %lu", touches.size());

    // this will return x, y coordinate
    Point location = touches.at(0)->getLocationInView();

    // convert this location to Cocos2d x, y coordinate
    location = Director::getInstance()->convertToGL(location);
    
    Sprite *sprite = Sprite::create("CloseNormal.png");
    sprite->setPosition(location);
    this->addChild(sprite, 1);
}

Accelerate a sprite with device acceleration

HelloWorldScene.h


public:

    Sprite *sprite;
    
    virtual void onAcceleration(Acceleration* acc, Event* event);

HelloWorldScene.cpp


bool HelloWorld::init()
{

    sprite = Sprite::create("CloseNormal.png");
    sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
    this->addChild(sprite);

    Device::setAccelerometerEnabled(true);
    auto accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(HelloWorld::onAcceleration, this));
    _eventDispatcher->addEventListenerWithSceneGraphPriority(accelerationListener, this);
}

void HelloWorld::onAcceleration(Acceleration *acc, Event *event)
{
    Size s = Director::getInstance()->getWinSize();
    
    /*
     * -1 <= pAccelerationValue <= 1
     * so we add +1 to make it, 0 <= pAccelerationValue <= 2
     * then divide by 2 to make it, 0 <= pAccelerationValue <= 1
     */
    float percentX = (acc->x + 1) / 2;
    float percentY = (acc->y + 1) / 2;
    
    // position the sprite exactly as how much device accelerated
    sprite->setPosition(Point(percentX * s.width, percentY * s.height));
}

Accelerate a sprite based on Sprite current Position

follow Accelerate a sprite with device acceleration

HelloWorldScene.cpp


void HelloWorld::onAcceleration(Acceleration *acc, Event *event)
{
    Size s = Director::getInstance()->getWinSize();
    
    // we can move the sprite based on the current sprite position
    // add accelerated value with the current position of sprite
    Point p = sprite->getPosition();
    sprite->setPosition(p + Point(acc->x, acc->y));
 
    // uncomment the following line and comment out the above line, to
    // speed up the movement of sprite
    // sprite->setPosition(p + Point(acc->x * 10, acc->y * 10));
}

Run Action: Move a Sprite to a touch location

HelloWorldScene.h


public:

    Sprite *sprite;
    
    void onTouchesBegan (const vector<Touch *> &touches, Event *event);

HelloWorldScene.cpp


bool HelloWorld::init()
{
    sprite = Sprite::create("CloseNormal.png");
    sprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
    this->addChild(sprite);

    auto touchListener = EventListenerTouchAllAtOnce::create();
    touchListener->onTouchesBegan = CC_CALLBACK_2(HelloWorld::onTouchesBegan, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
}

void HelloWorld::onTouchesBegan (const vector<Touch *> &touches, Event *event)
{
    CCLOG("onTouchesBegan called %lu", touches.size());
    
    Touch *touch = (Touch *) touches.at(0);
    
    Point location = touch->getLocationInView();
    location = Director::getInstance()->convertToGL(location);
    
    sprite->runAction(MoveTo::create(1, location));
}

Run Action: Scale up Sprite on touch on sprite

HelloWorldScene.cpp


void HelloWorld::onTouchesBegan (const vector<Touch *> &touches, Event *event)
{
    CCLOG("onTouchesBegan called %lu", touches.size());
    
    Touch *touch = (Touch *) touches.at(0);
    
    Point location = touch->getLocationInView();
    location = Director::getInstance()->convertToGL(location);
    
    if (sprite->getBoundingBox().containsPoint(location)) {
        sprite->runAction(ScaleTo::create(1, 1.2));
    }
}

Create a Sprite from Sprite-sheet

HelloWorldScene.cpp


bool HelloWorld::init()
{
    // load the sprite-sheet
    SpriteFrameCache::getInstance()->addSpriteFramesWithFile("plistFile.plist");

    // create the sprite from sprite frame name 
    Sprite *person = Sprite::createWithSpriteFrameName("ab001.png");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s