Cocos2d-x Example Code Snippets


Update:
Cocos2d-x: Version 3.x Example code snippets

Scale the background image to fill the Screen


// ask the director for window size
CCSize size = CCDirector::sharedDirector()->getWinSize();


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


// position the background image at the center of window
bgImage->setPosition(ccp(size.width / 2, size.height / 2));


// 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 window size
float rX = size.width / bgImage->getContentSize().width;
float rY = size.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 

// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
		"CloseNormal.png",
		"CloseSelected.png",
		this,
		menu_selector(HelloWorld::menuCloseCallback));


pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );


// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition( CCPointZero );
this->addChild(pMenu, 1);


// Step 2: Button click handler / listener 

// menu close callback method 
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

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

}

Get the touch Location

 
/*
 .h file content
 */

// we are going to override this method of CCLayer class 
void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);


// =========================================== // 


/*
 .cpp file content
 */

// add this line to init() method to enable touch  
this->setTouchEnabled(true);

void HelloWorld::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	CCTouch *touch = (CCTouch *)pTouches->anyObject();

	// this will return x, y coordinate
	CCPoint location = touch->getLocationInView();

	// convert this location to Cocos2d x, y coordinate
	location = CCDirector::sharedDirector()->convertToGL(location);
}

Create a Sprite to the touch Location

follow the Get the touch Location section first


void HelloWorld::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	CCTouch *touch = (CCTouch *)pTouches->anyObject();
    
	// this will return x, y coordinate
	CCPoint location = touch->getLocationInView();
    
	// convert this location to Cocos2d x, y coordinate
	location = CCDirector::sharedDirector()->convertToGL(location);
    
    // Create a sprite
    CCSprite *sprite = CCSprite::create("sprite_image.png");
    
    // on each touch, we are setting a sprite on the touch location
    sprite->setPosition(location);
    
    this->addChild(sprite, 1);
}

Accelerate a sprite with device acceleration


/*
 .h file content 
*/

cocos2d::CCSprite *aSprite;

void didAccelerate(cocos2d::CCAcceleration *pAccelerationValue);


/* 
.cpp file content 
*/

// in init() method 
this->setAccelerometerEnabled(true);

void HelloWorld::didAccelerate(cocos2d::CCAcceleration *pAccelerationValue)
{

	CCSize s = CCDirector::sharedDirector()->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 = (pAccelerationValue->x + 1) / 2;
	float percentY = (pAccelerationValue->y + 1) / 2;

	// position the sprite exactly as how much device accelerated
	aSprite->setPosition(ccp(percentX * s.width, percentY * s.height));

    // or, alternatively, we can move the sprite based on the current sprite position

	// add accelerated value with the current position of sprite
	CCPoint p = aSprite->getPosition();
	aSprite->setPosition(ccpAdd(p, ccp(pAccelerationValue->x, pAccelerationValue->y)));

	// speed up the movement of sprite
	aSprite->setPosition(ccpAdd(p, ccp(pAccelerationValue->x * 10, pAccelerationValue->y * 10)));

}

Run Action: Move a Sprite to a touch location

/*
.h file
*/

CCSprite *aSprite;

// touch listener 
void ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);


/*
.cpp file
*/

// init() method 

aSprite = CCSprite::create("sprite.png");
aSprite->setPosition(ccp(size.width / 2, size.height / 2));
this->addChild(aSprite, 1);

this->setTouchEnabled(true);

void HelloWorld::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	CCTouch *touch = (CCTouch *) pTouches->anyObject();

	CCPoint location = touch->getLocationInView();

	location = CCDirector::sharedDirector()->convertToGL(location);

	aSprite->runAction(CCMoveTo::create(1, location));
}

Run Action: Scale up Sprite on touch on sprite


void HelloWorld::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	CCTouch *touch = (CCTouch *) pTouches->anyObject();
	CCPoint location = touch->getLocationInView();
	location = CCDirector::sharedDirector()->convertToGL(location);
	
	if (aSprite->boundingBox().containsPoint(location))
	{
		aSprite->runAction(CCScaleTo::create(1, 1.2));
	}
}

Create a Sprite from Sprite-sheet


// load the sprite-sheet in init() method 
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("plist_file.plist");
    
// create the sprite from sprite frame name 
CCSprite *aSprite = CCSprite::createWithSpriteFrameName("cc001.png");

Run Action: Frame Animation


void HelloWorld::ccTouchesBegan(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent)
{
	// stop all previous animations before proceeding to avoid conflicts 
	aSprite->stopAllActions();

	// frames array 
	CCArray *frames = CCArray::create();

	for ( int i = 1; i <= 11; i++ ) {
		// generate the sequenced frame name 
		CCString *frame = CCString::createWithFormat("b%04d.png", i);
		CCLOG("frame name: %s", frame->getCString());
		
		// get the sprite frame from the sprite-sheet and add it to the array 
		frames->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(frame->getCString()));
	}

	// create sprite frame animation with frames array and speed 
	aSprite->runAction(CCAnimate::create(CCAnimation::createWithSpriteFrames(frames, .05)));
}

Load Hi or low resolution artwork


// ask director the window size
CCSize size = CCDirector::sharedDirector()->getWinSize();

CCString *file = size.width > 480 ? CCString::create("bg_hd.png") : CCString::create("bg.png");

CCSprite *bgImage = CCSprite::create(file->getCString());

// same goes for sprite-sheet 
file = size.width > 480 ? CCString::create("plist_file_hd.png") : CCString::create("plist_file.png");

CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(file->getCString());

Place a button with a buttonHandler


// inside init() method, creating a button from a sprite 
CCMenuItemSprite *btn = CCMenuItemSprite::create(
		// button default image 
		CCSprite::createWithSpriteFrameName("button_img.png"),	
		NULL, 		// button selected image, NULL means same as default 
		this, 		// this layer will run the method 
		menu_selector(HelloWorld::buttonHandler));		// button click handler 

// CCMenu is an Array; specifically Array of buttons; 
// add the button; NULL means we are done  
CCMenu *pMenu = CCMenu::create(btn, NULL);	

this->addChild(pMenu, 1);

// button Handler
void HelloWorld::buttonHandler() {

	// write button click action 
	
	// toggle the visibility of a Sprite 
	aSprite->setVisible(!aSprite->isVisible());
}

Play a sound


// step 1
#include "SimpleAudioEngine.h"

// step 2
using namespace CocosDenshion;

// step 3
// Preload the sound effect in init() method for performance 
SimpleAudioEngine::sharedEngine()->preloadEffect("sound.wav");

// step 4
SimpleAudioEngine::sharedEngine()->playEffect("sound.wav");

Show Android log


// add this line at the top of your .cpp file .. before everything, the number 1 line 
#define COCOS2D_DEBUG 1

// write log anywhere in your code 
CCLOG("I am here %s", "whats up");
CCLOG("this::start called");

// see the log in logCat with tag:cocos2d-x

Enable Sprite-sheet pvr.ccz files

For more info: See here


bool AppDelegate::applicationDidFinishLaunching()
{
	// initialize director
	CCDirector *pDirector = CCDirector::sharedDirector();
	
	
    pDirector->setOpenGLView(&CCEGLView::sharedOpenGLView());
    
    // enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
    pDirector->enableRetinaDisplay(true);

	// sets landscape mode
	pDirector->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);

	// turn on display FPS
	pDirector->setDisplayStats(false);
	
	// if we use pvr.ccz file types for sprite-sheet then we need to add this line
	CCTexture2D::PVRImagesHavePremultipliedAlpha(true);
	
	// set FPS. the default value is 1.0/60 if you don't call this
	pDirector->setAnimationInterval(1.0 / 60);
	
	// create a scene. it's an autorelease object
	CCScene *pScene = HelloWorldScene::scene();

	// run
	pDirector->runWithScene(pScene);

	return true;
}

Application wide scale factor

Project/jni/hellocpp/main.cpp file


void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv*  env, jobject thiz, jint w, jint h)
{
    if (!CCDirector::sharedDirector()->getOpenGLView())
    {
        CCEGLView *view = CCEGLView::sharedOpenGLView();
        view->setFrameSize(w, h);
        
        // if the height of the screen is >= 480 we should use the scale factor 2
        int artScaleFactor = (h >= 480) ? 2 : 1;
        
        // scale value, based on the standard height (320) of our artwork design
        // you can set appropriate value for your project 
        float scale = (float) h / (float) (320 * artScaleFactor);
        
        // save the above to variable in a singleton Utility class for easy access
        Utils::setArtScaleFactor(artScaleFactor);
        Utils::setScale(scale);

        AppDelegate *pAppDelegate = new AppDelegate();
        CCApplication::sharedApplication()->run();
    }
    else
    {
        ccDrawInit();
        ccGLInvalidateStateCache();
        
        CCShaderCache::sharedShaderCache()->reloadDefaultShaders();
        CCTextureCache::reloadAllTextures();
        CCNotificationCenter::sharedNotificationCenter()->postNotification(EVNET_COME_TO_FOREGROUND, NULL);
        CCDirector::sharedDirector()->setGLDefaultValues(); 
    }
}

Crete a Sprite Button with Image and Style


bool GameButton::initWithText(const char * text, bool isBig)
{
    if (!CCSprite::init()) {
        return false;
    }
    
    // get image name based on the isBig parameter 
    CCString* btnFrame = (isBig) ? 
    		CCString::create("button_big.png") : CCString::create("button_small.png");
    
    // font size will be set based on scale factor, it will be either 1, 2
    // that is, fontSize will be either 18 or 32 
    // @see previous scale factor snippet 
    int fontSize = 18 * Utils::getArtScaleFactor();
    
    // sprite will display this frame
    // we can change the displayed frame at runtime using this set method 
    this->setDisplayFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(btnFrame->getCString()));
    
    // Text Label to show on the button 
    // FONT_MAIN = is a constant, we declared with value of our main font name 
    CCLabelTTF *label = CCLabelTTF::create(text, CCString::createWithFormat("%s.ttf",FONT_MAIN)->getCString(), fontSize + isBig * fontSize);
    
    // set the label in the middle 
    label->setPosition(ccp(this->getContentSize().width/2,this->getContentSize().height/2));
    this->addChild(label,1);
    
    // Display a shadow of the label 
    // create a same label instance 
    CCLabelTTF *labelShadow = CCLabelTTF::create(text, CCString::createWithFormat("%s.ttf",FONT_MAIN)->getCString(), fontSize + isBig * fontSize);
    
    // set the position a little bit below of the original label 
    labelShadow->setPosition(ccp(this->getContentSize().width/2 - (2 + isBig * 2),this->getContentSize().height/2));
    
    // set the color black or a grey (you choose) 
    labelShadow->setColor(ccBLACK);
    
    // set opacity a little low value (valid value of opacity is 0 to 255) 
    labelShadow->setOpacity(150);
    
    // add child below the original level z position 
    this->addChild(labelShadow,0);
    
    // scale the sprite based on our standard scale value 
    this->setScale(Utils::getScale());

    return true;
}

Usage of the above game button


GameButton* GameButton::buttonWithText(const char * text, bool isBig)
{
    GameButton *btn = new GameButton();
    btn->initWithText(text, isBig);
    btn->autorelease();
    return btn;
}

Utility method: Run animation with Frames


/**
 * Pass the animation frame image starting and ending number 
 * 
 */
cocos2d::CCAnimate* Utils::getAnimationWithFrames(int from, int to)
{
	CCArray* frames = CCArray::create();
	for (int i = from; i <= to; i++) {

		// generate the file names 
		CCString *str = CCString::createWithFormat("a%04d.png", i);
		
		// add the sprite frame to the array 
		frames->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(str->getCString()));
	}
	
	CCAnimation *animation = CCAnimation::create(frames, 1.0f/24.0f);
	CCAnimate *a = CCAnimate::create(animation);
	
	return a;
}

Utility method: Scale the background image to fill entire screen


/**
 * For background images 
 * scales the background images to the entire screen 
 */
void Utils::scaleSprite(CCSprite* sprite)
{
	float rX = Utils::s().width / sprite->getContentSize().width;
	float rY = Utils::s().height / sprite->getContentSize().height;
	sprite->setScaleX(rX);
	sprite->setScaleY(rY);
}

Advertisements

2 thoughts on “Cocos2d-x Example Code Snippets

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