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");
}

Advertisements

Cocos2dx: Call Java code from C++ or Call C++ code from Java using JNI


Call Java code from C++

Step 1: Include Jni folder

  • Right click on project => Properties => C/C++ General => Paths and Symbols => (Right side) Select Source Location => Click Link Folder => Check Link to folder in the file system => Browse /Cocos2d/cocos2dx/platform/android/jni => Open
  • If the folder already existed in Source location then and error will show up, “The folder ‘jni’ already exists.” => Cancel
    otherwise, click OK

Step 2: Create Cpp class

  • Create a Cpp class (both .h and .cpp) named JniLink.h and JniLink.cpp in /Cocos2d/cocos2dx/platform/android/jni/

JniLink.h

/*
 * JniLink.h
 */

#ifndef JNILINK_H_
#define JNILINK_H_

extern "C"
{
	extern void openURL(const char* url);
}

#endif /* JNILINK_H_ */

JniLink.cpp


/*
 * JniLink.cpp
 */


#include "JniLink.h"
#include "JniHelper.h"

using namespace cocos2d;

extern "C"
{

	void openURL(const char* url)
	{
		JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t,
				"org/cocos2dx/lib/Cocos2dxActivity", 	// fully qualified class name
				"openURL", 								// method name
				"(Ljava/lang/String;)V")) {				// data type of argument

			// jstring - C++ representation of Java String
			jstring stringArg = t.env->NewStringUTF(url);

			// call the method, with arguments
			t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg);
		}
	}
}

Step 3: Java code

  • Open Java class from Project src/org/cocos2dx/lib/Cocos2dxActivity
  • Change the code like following

Cocos2dxActivity.java


package org.cocos2dx.lib;

import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
	// ===========================================================
	// Constants
	// ===========================================================

	private static final String TAG = Cocos2dxActivity.class.getSimpleName();

	// ===========================================================
	// Fields
	// ===========================================================
	
	private Cocos2dxGLSurfaceView mGLSurfaceView;
	private Cocos2dxHandler mHandler;
	private static Activity self = null;

	// ===========================================================
	// Constructors
	// ===========================================================

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.self = this;
		
    	this.mHandler = new Cocos2dxHandler(this);

    	this.mGLSurfaceView = onCreateView();

		Cocos2dxHelper.init(this, this);
	}

   public static void openURL (String url) {
    	Intent aIntent = new Intent (Intent.ACTION_VIEW);
    	aIntent.setData(Uri.parse(url));
    	self.startActivity(aIntent);
    }

Step 4: Add the class to the Android.mk file

  • Open Android.mk file from Project jni/Android.mk
  • Add the newly added JniLink.cpp class reference like following

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := game_shared

LOCAL_MODULE_FILENAME := libgame

LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   /../../../cocos2dx/platform/android/jni/JniLink.cpp \
                   ../../Classes/HelloWorldScene.cpp
                   
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
					$(LOCAL_PATH)/../../../cocos2dx/platform/android/jni               

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static
            
include $(BUILD_SHARED_LIBRARY)

$(call import-module,CocosDenshion/android) \
$(call import-module,cocos2dx) \
$(call import-module,extensions)

Step 5: Call the Java method from a Layer: HelloWorldScene.cpp

  • Include JniLink.h file to HelloWorldScene.cpp file
    #include "JniLink.h"
  • call method
    openURL("http://www.bing.com");
    from init() method

=============================================================================

Call C++ method from Java

Step 1: Create a cpp class

  • Create a cpp class (both .h and .cpp) named JniExample

JniExample.h


/*
 * JniExample.h
 */

#ifndef JNIEXAMPLE_H_
#define JNIEXAMPLE_H_


extern "C"
{
	void showMessageBoxJNI(const char * pszMsg, const char * pszTitle);
}

#endif /* JNIEXAMPLE_H_ */

JniExample.cpp


/*
 * JniExample.cpp
 */

#include "JniHelper.h"
#include "cocos2d.h"
#include "JniExample.h"

using namespace cocos2d;

extern "C"
{

	// the method name is required to be follow the fully qualified package format
	jstring Java_org_cocos2dx_lib_Cocos2dxActivity_nativeExample(JNIEnv * env, jobject thiz)
	{
		return env->NewStringUTF("Hello from C++");
	}

	// this method will call a Java method named "showMessageBox"
	void showMessageBoxJNI(const char * pszMsg, const char * pszTitle)
	{
		if (! pszMsg)
		{
			return;
		}
	
		JniMethodInfo t;
	
		if (JniHelper::getStaticMethodInfo(t
				, "org/cocos2dx/lib/Cocos2dxActivity"
				, "showMessageBox"
				, "(Ljava/lang/String;Ljava/lang/String;)V"))
		{
			jstring stringArg1;
	
			if (! pszTitle)
			{
				stringArg1 = t.env->NewStringUTF("");
			}
			else
			{
				stringArg1 = t.env->NewStringUTF(pszTitle);
			}
	
			jstring stringArg2 = t.env->NewStringUTF(pszMsg);
			t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2);
	
			t.env->DeleteLocalRef(stringArg1);
			t.env->DeleteLocalRef(stringArg2);
			t.env->DeleteLocalRef(t.classID);
		}
	}
}

Step 2: Add JniExample.cpp to Android.mk

  • Carefully notice the class indicate sequence. “JniExample.cpp” is alphabetically smaller and need to be placed before “JniLink.cpp”

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := game_shared

LOCAL_MODULE_FILENAME := libgame

LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../Classes/AppDelegate.cpp \
                   /../../../cocos2dx/platform/android/jni/JniExample.cpp \
                   /../../../cocos2dx/platform/android/jni/JniLink.cpp \
                   ../../Classes/HelloWorldScene.cpp
                   
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
					$(LOCAL_PATH)/../../../cocos2dx/platform/android/jni               

LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static cocos_extension_static
            
include $(BUILD_SHARED_LIBRARY)

$(call import-module,CocosDenshion/android) \
$(call import-module,cocos2dx) \
$(call import-module,extensions)


Step 3: Update Cocos2dxActivity.java class

package org.cocos2dx.lib;

import org.cocos2dx.lib.Cocos2dxHandler.DialogMessage;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
	// ===========================================================
	// Constants
	// ===========================================================

	private static final String TAG = Cocos2dxActivity.class.getSimpleName();

	// ===========================================================
	// Fields
	// ===========================================================
	
	private Cocos2dxGLSurfaceView mGLSurfaceView;
	private Cocos2dxHandler mHandler;
	private static Activity self = null;
	private final static int HANDLER_SHOW_DIALOG = 1;
	private static Handler handler;

	// ===========================================================
	// Constructors
	// ===========================================================

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.self = this;
		
    	this.mHandler = new Cocos2dxHandler(this);

    	this.mGLSurfaceView = onCreateView();

		Cocos2dxHelper.init(this, this);
		
		handler = new Handler(){
        	public void handleMessage(Message msg){
        		switch(msg.what){
        		case HANDLER_SHOW_DIALOG:
        			showDialog(((DialogMessage)msg.obj).titile, ((DialogMessage)msg.obj).message);
        			break;
        		}
        	}
        };
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	protected void onResume() {
		super.onResume();

		Cocos2dxHelper.onResume();
		this.mGLSurfaceView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();

		Cocos2dxHelper.onPause();
		this.mGLSurfaceView.onPause();
	}

	@Override
	public void showDialog(final String pTitle, final String pMessage) {
		Message msg = new Message();
		msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
		msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
		this.mHandler.sendMessage(msg);
	}

	@Override
	public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) { 
		Message msg = new Message();
		msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
		msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
		this.mHandler.sendMessage(msg);
	}
	
	@Override
	public void runOnGLThread(final Runnable pRunnable) {
		this.mGLSurfaceView.queueEvent(pRunnable);
	}

	// ===========================================================
	// Methods
	// ===========================================================
	
    public Cocos2dxGLSurfaceView onCreateView() {
    	// Init handler
    			
    	// FrameLayout
        ViewGroup.LayoutParams framelayout_params =
            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                                       ViewGroup.LayoutParams.FILL_PARENT);
        FrameLayout framelayout = new FrameLayout(this);
        framelayout.setLayoutParams(framelayout_params);

        // Cocos2dxEditText layout
        ViewGroup.LayoutParams edittext_layout_params =
            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                                       ViewGroup.LayoutParams.WRAP_CONTENT);
        Cocos2dxEditText edittext = new Cocos2dxEditText(this);
        edittext.setLayoutParams(edittext_layout_params);

        // ...add to FrameLayout
        framelayout.addView(edittext);

        // Cocos2dxGLSurfaceView
        Cocos2dxGLSurfaceView gLSurfaceView = new Cocos2dxGLSurfaceView(this);

        // ...add to FrameLayout
        framelayout.addView(gLSurfaceView);

        gLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
        gLSurfaceView.setCocos2dxEditText(edittext);

        // Set framelayout as the content view
		setContentView(framelayout);
		
		return gLSurfaceView;
    }
    
    public static void openURL (String url) {
    	Intent aIntent = new Intent (Intent.ACTION_VIEW);
    	aIntent.setData(Uri.parse(url));
    	self.startActivity(aIntent);
    }
    
    public static void showMessageBox(String title, String message) 
    {
    	
    	Message msg = new Message();
    	msg.what = HANDLER_SHOW_DIALOG;
    	
    	// calling this nativeExample() method from C++ 
    	msg.obj = new DialogMessage(title, nativeExample());
    	Log.d("tag", "I am here " + nativeExample());
    	handler.sendMessage(msg);
    }
    
    // This method body exists in C++, need to have "native" keyword 
    private static native String nativeExample();

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}

Step 4: Call from HelloWorldScene

  • include
    #include "JniExample.h"
  • Call the method
    showMessageBoxJNI("You shouldn't see this", "Java -> C++");

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);
}