●게임 중 화면을 정지 버튼을 누르면 일시정지하고 팝업창을 띄운다. 팝업창에서 버튼은 누르면 다시 게임 화면으로 돌아간다. 팝업창을 띄우고 게임상의 액션,스케줄을 멈추고 재시작하기 위해 " CCDirector::sharedDirector()->pause(); " 을 사용하고 정지버튼터치를 비활성하기 위해 " CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(pMenu, kCCMenuHandlerPriority,true); "를 사용한다. 팝업창이 열렸을때, 닫혔을때 구분해서 함수를 실행하기 위해 노티피케이션(Notification)을 이용한다. 노티피케이션은 클래스사이에서 메시지를 주고 받고 하는 싱클톤 객체이다.





●예제

- HelloWorldScene.h


#ifndef __HELLOWORLD_SCENE_H__

#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"


class HelloWorld : public cocos2d::CCLayerColor

{

public:

    virtual bool init();


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(HelloWorld);

cocos2d::CCMenu* pMenu ;


void HelloWorld::doPop(CCObject* pSender);

void HelloWorld::doNotification(CCObject *obj);


};


#endif // __HELLOWORLD_SCENE_H__

 




- HelloWorldScene.cpp


#include "HelloWorldScene.h"

#include "PopLayer.h"


using namespace cocos2d;


CCScene* HelloWorld::scene()

{

    CCScene *scene = CCScene::create();

    

    HelloWorld *layer = HelloWorld::create();


    scene->addChild(layer);


    return scene;

}


bool HelloWorld::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(255, 255, 255, 255)) )

    {

        return false;

    }

////////////////////////


//메뉴 추가

CCMenuItemFont* itemPop=CCMenuItemFont::create("popUp", this, 

menu_selector(HelloWorld::doPop));

itemPop->setColor(ccc3(0,0,0));

//CCMenu* pMenu=CCMenu::create(itemPop, NULL);

pMenu=CCMenu::create(itemPop, NULL);

pMenu->setPosition(ccp(240, 50));

this->addChild(pMenu);

//스프라이트 추가

CCSprite* man=CCSprite::create("images/grossini.png");

man->setPosition( ccp(20,250));

this->addChild(man);


//액션 추가

CCActionInterval* myAction=CCMoveBy::create(15, ccp(400, 0));

man->runAction(myAction);



//노티피케이션 추카

CCNotificationCenter::sharedNotificationCenter()->addObserver(this,

callfuncO_selector(HelloWorld::doNotification),

"notification", NULL);

          //"notification"이라는 메시지가 오면 해당 함수를 실행한다.


    return true;

}


void HelloWorld::doPop(CCObject* pSender){

CCScene* pScene=PopLayer::scene();

this->addChild(pScene,2000,2000);



}

//노티피케이션 함수

void HelloWorld::doNotification(CCObject *obj){

      //노티피케이션 받기

CCString *pParam=(CCString*)obj;

CCLog("notification %s", pParam->getCString());

if(pParam->intValue()==1){

CCLog("noti 11");

CCDirector::sharedDirector()->resume();   //화면 재시작


CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(pMenu, kCCMenuHandlerPriority,true);

                                     //메뉴 버튼 활성

}

else{

CCArray* childs = this->getChildren();

CCLog("noti 00");

CCDirector::sharedDirector()->pause();   //화면 정지


CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(pMenu);

                                      //메뉴버튼 비활성

}


}

 





- PopLayer.h


#ifndef __PopLayer__

#define __PopLayer__


#include "cocos2d.h"


class PopLayer : public cocos2d::CCLayerColor

{

public:

    virtual bool init();


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(PopLayer);

cocos2d::CCSize winSize;

CCLayerColor* backLayer;

CCLayerColor* popUpLayer;

void PopLayer::doClose(CCObject* pSender);

};

#endif // _PopLayer__





- PopLayer.cpp


#include "PopLayer.h"

#include "HelloWorldScene.h"


using namespace cocos2d;


CCScene* PopLayer::scene()

{

    CCScene *scene = CCScene::create();

    

    PopLayer *layer = PopLayer::create();


    scene->addChild(layer);


    return scene;

}


bool PopLayer::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(0, 0, 0, 0)) )  //투명하게

    {

        return false;

    }

////////////////////////


CCString* popParam=CCString::create("0");

CCNotificationCenter::sharedNotificationCenter()->postNotification("notification", popParam);         //노티피케이션 보내기


winSize=CCDirector::sharedDirector()->getWinSize();

//메뉴추가

CCMenuItemFont* pMenuItem=CCMenuItemFont::create("close", this, 

menu_selector(PopLayer::doClose) );

pMenuItem->setColor(ccc3(0,0,0));

CCMenu* pMenu2=CCMenu::create(pMenuItem, NULL);

pMenu2->setPosition(ccp(240, 100));

this->addChild(pMenu2,10);


//backLayer추가

backLayer=CCLayerColor::create(ccc4(0,0,0,50), winSize.width, winSize.height);

backLayer->setAnchorPoint(ccp(0,0));

backLayer->setPosition(ccp(0,0));

this->addChild(backLayer);


//popUpLayer추가

popUpLayer=CCLayerColor::create(ccc4(255,0,0,255), 250,150);

popUpLayer->setAnchorPoint(ccp(0,0));

popUpLayer->setPosition(ccp((winSize.width-popUpLayer->getContentSize().width)/2, 

(winSize.height-popUpLayer->getContentSize().height)/2,   )  );

this->addChild(popUpLayer);


    return true;

}



void PopLayer::doClose(CCObject* pSender)

{

CCString* popParam=CCString::create("1");

CCNotificationCenter::sharedNotificationCenter()->postNotification("notification", popParam);         //노티피케이션 보내기


//팝업창 제거

this->removeFromParentAndCleanup(true);


}












Posted by -현's-

댓글을 달아 주세요



StageIdx.h


#ifndef __StageIdx__H__

#define __StageIdx__H__


#include "cocos2d.h"

//싱글톤 클래스

using namespace cocos2d;


class StageIdx : public cocos2d::CCLayer

{

public:

static StageIdx *getInstance();

void setStage2true();

bool getStage2Bool();


private:

StageIdx();

~StageIdx();

};


#endif  // __StageIdx__H__




StageIdx.cpp


#include "StageIdx.h"


StageIdx::StageIdx(void)

{

CCUserDefault::sharedUserDefault()->setBoolForKey("stage2",false);

CCUserDefault::sharedUserDefault()->flush();

}


StageIdx::~StageIdx(void)

{

}


static StageIdx *gameData;


StageIdx* StageIdx::getInstance()

{

if(!gameData)

{

gameData=new StageIdx();

}

return gameData;

}


bool StageIdx::getStage2Bool()

{

bool stage2= CCUserDefault::sharedUserDefault()->getBoolForKey("stage2");

return stage2;

}


void StageIdx::setStage2true(){

CCUserDefault::sharedUserDefault()->setBoolForKey("stage2",true);

CCUserDefault::sharedUserDefault()->flush();

}










Stage1Layer.h


#ifndef __Stage1Layer__H__

#define __Stage1Layer__H__


#include "cocos2d.h"


using namespace cocos2d;


class Stage1Layer : public cocos2d::CCLayer

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();


    CREATE_FUNC(Stage1Layer);


bool jumpYN;


CCSprite *abc;


int score;

//void Stage1Layer::gameMenuStart(CCObject* sender);

void Stage1Layer::createDragon();


CCSprite* dragon;


void Stage1Layer::createBackground();

~Stage1Layer();

CCArray* stoneArray;

CCArray* coinArray;


CCLabelTTF* pLabel;


char coinScore[100];

void Stage1Layer::stoneCollision(float dt);

void Stage1Layer::coinCollision(float dt);


void Stage1Layer::winGame();


CCAction* rep;

void Stage1Layer::ccTouchesEnded(CCSet *pTouches, CCEvent* event);

};


#endif  // __Stage1Layer__H__




Stage1Layer.cpp


#include "Stage1Layer.h"

#include "StageIdx.h"

#include "WinLayer.h"

#include "LoseLayer.h"



CCScene* Stage1Layer::scene()

{

    CCScene *scene = CCScene::create();

    

    Stage1Layer *layer = Stage1Layer::create();

    

    // 960 x 640

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    if (winSize.width >= 960) {

        layer->setScale(2.0);

        layer->setAnchorPoint(ccp(0.0, 0.0));

    }


    scene->addChild(layer);


    return scene;

}


bool Stage1Layer::init()

{

    if ( !CCLayer::init() )

    {

        return false;

    }

    

    /////////////////////////////

char coinScore[100] = {0};

score=0;

this->setTouchEnabled(true);

stoneArray=CCArray::createWithCapacity(4);

stoneArray->retain();


coinArray=CCArray::createWithCapacity(4);

coinArray->retain();

jumpYN=false;

CCTexture2D* texture1;

texture1=CCTextureCache::sharedTextureCache()->addImage("Images/white-512x512.png"); 

abc=CCSprite::createWithTexture(texture1, CCRectMake(0,0,20,10));

abc->setAnchorPoint(ccp(0,0));

abc->setColor(ccc3(255,255,0));

abc->setOpacity(255);

CCActionInterval* gogo = CCMoveBy::create(10, ccp(700, 0));

abc->runAction(gogo);



this->addChild(abc, 11);

this->createDragon();          //드래곤을 추가한다.

this->createBackground(); //배경 추가




this->schedule(schedule_selector(Stage1Layer::stoneCollision), 2.0f/60.0f);

this->schedule(schedule_selector(Stage1Layer::coinCollision), 2.0f/60.0f);



//레이블 생성 및 초기화

pLabel=CCLabelTTF::create("score:0", "Thonburi", 30);

       //레이블 내용은 HelloWorld이고 폰트는 Thonburi, 크기는 20이다.

//레이블 위치 지정

        pLabel->setPosition(ccp(90,50));

//레이블 색 지정

pLabel->setColor(ccc3(255,255,255));

        //흰색( ccc(255,255,255) )이 기본색이다. 

//레이블의 투명도 지정

pLabel->setOpacity(100.0);

//레이어에 레이블 객체 추가

this->addChild(pLabel, 12);


    return true;

}


Stage1Layer::~Stage1Layer()

{

stoneArray->release();

coinArray->release();

}



void Stage1Layer::stoneCollision(float dt){

CCObject *Obj;

CCLog("stoneCollisition");

CCARRAY_FOREACH(stoneArray, Obj){

CCSprite *stone=(CCSprite*)Obj;

if(255 == stone->getOpacity()){

int abcX = abc->getPositionX();

CCLog("stoneCollisition22222");

CCRect rectA=dragon->boundingBox();

int aa=rectA.getMinX();

int bb=rectA.getMinY();

CCLog("stoneCollisitionaaaa %d %d",aa,bb);

CCRect rectB=stone->boundingBox();

CCLog("stoneCollisitionbbbb");

int cc=rectB.getMinX()-abcX;

int dd=rectB.getMinY();

rectA.setRect(aa+30,bb,100,140);

rectB.setRect(cc,dd,20,10);

CCLog("stoneCollisitioncdcdcd %d %d",cc,dd);

if(rectA.intersectsRect(rectB)){

CCLog("stoneCollisition33333");

this->unscheduleAllSelectors();

CCScene* pScene=LoseLayer::scene();

CCDirector::sharedDirector()->replaceScene(pScene);//기존장면 없애고 새장면 교체

}

}

}

CCLog("stoneCollisition444");

}



void Stage1Layer::coinCollision(float dt){

CCObject *Obj;

CCLog("coinCollisition");

CCARRAY_FOREACH(coinArray, Obj){

CCSprite *coin=(CCSprite*)Obj;

if(255 == coin->getOpacity()){

int abcX = abc->getPositionX();

CCLog("coinCollisition22222");

CCRect rectA=dragon->boundingBox();

int aa=rectA.getMinX();

int bb=rectA.getMinY();

CCLog("coinCollisitionaaaa %d %d",aa,bb);

CCRect rectB=coin->boundingBox();

CCLog("coinCollisitionbbbb");

int cc=rectB.getMinX()-abcX;

int dd=rectB.getMinY();

rectA.setRect(aa+30,bb,100,140);

rectB.setRect(cc,dd,10,10);

CCLog("coinCollisitioncdcdcd %d %d",cc,dd);

if(rectA.intersectsRect(rectB)){

CCLog("coinCollisition33333");

score++;

sprintf(coinScore, "score: %d",score);

coin->setOpacity(0);

pLabel->setString(coinScore);

CCLog("Score %d",score);


}

}

}

CCLog("stoneCollisition444");

}



void Stage1Layer::createBackground()

{

//배경 스프라이트1

CCSprite* background1 = CCSprite::create("Images/game_background1.jpg");

background1->setAnchorPoint(ccp(0,0));

//배경 스프라이트2

CCSprite* background2 = CCSprite::create("Images/game_background2.jpg");

background2->setAnchorPoint(ccp(0,0));


//패럴랙스노드를 만든다.

CCParallaxNode* voidNode = CCParallaxNode::create();


//배경 스트라이트를 패럴랙스노드에 넣는다.

voidNode->addChild(background1, 1, ccp(1.0f, 0.0f), ccp(0,0));

voidNode->addChild(background2, 1, ccp(1.0f, 0.0f), ccp(480,0));


//장애물 추가

CCTexture2D* texture;

texture=CCTextureCache::sharedTextureCache()->addImage("Images/white-512x512.png");

for(int i=1; i<4;i++)

{

CCSprite* stone=CCSprite::createWithTexture(texture, CCRectMake(0,0,20,10));

stone->setAnchorPoint(ccp(0,0));

stone->setColor(ccc3(75,255,0));

voidNode->addChild(stone, 1, ccp(1.0f, 0.0f), ccp(i*250, 200));

stoneArray->addObject(stone);


}

//코인 추가

for(int i=1; i<4;i++)

{

CCSprite* coin=CCSprite::createWithTexture(texture, CCRectMake(0,0,20,10));

coin->setAnchorPoint(ccp(0,0));

coin->setColor(ccc3(255,255,0));

voidNode->addChild(coin, 1, ccp(1.0f, 0.0f), ccp(i*250, 300));

coinArray->addObject(coin);


}

//액션

CCActionInterval* go = CCMoveBy::create(10, ccp(-700, 0));

CCFiniteTimeAction* seq = CCSequence::create(go,

CCCallFunc::create(this, callfunc_selector(Stage1Layer::winGame)),   //끝까지 이동하면 winGame로 이동

NULL);


voidNode->runAction(seq);

this->addChild(voidNode);

}



void Stage1Layer::winGame(){

//winGame화면으로 이동

StageIdx::getInstance()->setStage2true();    //stage2를 열수있게 true로 바꾼다.

CCScene* pScene=WinLayer::scene();

CCDirector::sharedDirector()->replaceScene(pScene);//기존장면 없애고 새장면 교체

}








void Stage1Layer::createDragon()

{ //움직이는 용 추가

jumpYN=false;

CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage("Images/dragon_animation.png");

CCAnimation *animation=CCAnimation::create();

animation->setDelayPerUnit(0.1);


for(int i=0; i<6; i++)

{

int index = i%4;

int rowIndex=i/4;


animation->addSpriteFrameWithTexture(texture, CCRectMake(index*130, rowIndex*140, 130, 140));

}

//스프라이트 생성

dragon=CCSprite::createWithTexture(texture, CCRectMake(0,0,130,140));

dragon->setPosition(ccp(100,240));

this->addChild(dragon,10);

dragon->setFlipX(true);


CCAnimate *animate=CCAnimate::create(animation);

CCAction* rep=CCRepeatForever::create(animate);

dragon->runAction(rep);

}


void Stage1Layer::ccTouchesEnded(CCSet *pTouches, CCEvent* event)

{

if(!jumpYN){          //현재 점프중이 아니면 해당 if문 실행

jumpYN=true;      //jumpYN을 true로 바꿔줌.


CCLog("TOUCH");


//추가

this->removeChild(dragon, true);  //

//추가end

//점프하면서 움직이는 용 추가

CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage("Images/dragon_animation.png");

CCAnimation *animation=CCAnimation::create();

animation->setDelayPerUnit(0.1);


for(int i=0; i<6; i++)

{

int index = i%4;

int rowIndex=i/4;


animation->addSpriteFrameWithTexture(texture, CCRectMake(index*130, rowIndex*140, 130, 140));

}

//스프라이트 생성

dragon=CCSprite::createWithTexture(texture, CCRectMake(0,0,130,140));

dragon->setPosition(ccp(100,240));

this->addChild(dragon);

dragon->setFlipX(true);


CCAnimate *animate=CCAnimate::create(animation);

CCAction* rep=CCRepeatForever::create(animate);

CCActionInterval* jump=CCJumpBy::create(2.5, ccp(0,0),110, 1 );

CCFiniteTimeAction* spw=CCSpawn::create(jump,rep, NULL);

CCFiniteTimeAction* seq=CCSequence::create(spw,  

CCCallFuncND::create(this, callfuncND_selector(CCNode::removeChild), dragon), 

CCCallFunc::create(this, callfunc_selector(Stage1Layer::createDragon)), 

NULL);

dragon->runAction(seq);

}else{

//jumpYN이 true면 점프 실행 안함

}

}










●Stage2Layer - Stage1Layer 이랑 비슷함








WinLayer.h


#ifndef __WinLayer__H__

#define __WinLayer__H__


#include "cocos2d.h"


using namespace cocos2d;


class WinLayer : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();



    CREATE_FUNC(WinLayer);

void WinLayer::mainMenuGo(CCObject* sender);



};


#endif  // __WinLayer__H__




WinLayer.cpp


#include "WinLayer.h"

#include "MainMenuLayer.h"


CCScene* WinLayer::scene()

{

    CCScene *scene = CCScene::create();

    

    WinLayer *layer = WinLayer::create();

    

    // 960 x 640

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    if (winSize.width >= 960) {

        layer->setScale(2.0);

        layer->setAnchorPoint(ccp(0.0, 0.0));

    }


    scene->addChild(layer);

    

    return scene;

}


bool WinLayer::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(255,255,255,255)) )

    {

        return false;

    }

    

    /////////////////////////////

CCMenuItemFont *newGame=CCMenuItemFont::create("Win!!! Mene go", this, menu_selector(WinLayer::mainMenuGo));

newGame->setColor(ccc3(0,0,0));

CCMenu* menu=CCMenu::create(newGame,NULL);

menu->setPosition(ccp(240,180));

this->addChild(menu);


    return true;

}



void WinLayer::mainMenuGo(CCObject* sender)

{

CCScene* pScene=MainMenuLayer::scene();

CCDirector::sharedDirector()->replaceScene(pScene);

}










●LoseLayer.h


#ifndef __LoseLayer__H__

#define __LoseLayer__H__


#include "cocos2d.h"


using namespace cocos2d;


class LoseLayer : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();



    CREATE_FUNC(LoseLayer);

void LoseLayer::mainMenuGo(CCObject* sender);



};


#endif  // __LoseLayer__H__





●LoseLayer.cpp


#include "LoseLayer.h"

#include "MainMenuLayer.h"


CCScene* LoseLayer::scene()

{

    CCScene *scene = CCScene::create();

    

    LoseLayer *layer = LoseLayer::create();

    

    // 960 x 640

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    if (winSize.width >= 960) {

        layer->setScale(2.0);

        layer->setAnchorPoint(ccp(0.0, 0.0));

    }


    scene->addChild(layer);

    

    return scene;

}


bool LoseLayer::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(255,255,255,255)) )

    {

        return false;

    }

    

    /////////////////////////////

CCMenuItemFont *newGame=CCMenuItemFont::create("Lose...Mene go", this, menu_selector(LoseLayer::mainMenuGo));

newGame->setColor(ccc3(0,0,0));

CCMenu* menu=CCMenu::create(newGame,NULL);

menu->setPosition(ccp(240,180));

this->addChild(menu);


    return true;

}



void LoseLayer::mainMenuGo(CCObject* sender)

{

CCScene* pScene=MainMenuLayer::scene();

CCDirector::sharedDirector()->replaceScene(pScene);



}











Posted by -현's-

댓글을 달아 주세요



AppDelegate.h


#ifndef __APP_DELEGATE_H__

#define __APP_DELEGATE_H__


#include "cocos2d.h"


class  AppDelegate : private cocos2d::CCApplication

{

public:

    AppDelegate();

    virtual ~AppDelegate();

    virtual bool applicationDidFinishLaunching();


    virtual void applicationDidEnterBackground();


    virtual void applicationWillEnterForeground();

};


#endif  // __APP_DELEGATE_H__

 





AppDelegate.cpp


#include "cocos2d.h"

#include "AppDelegate.h"

#include "LoadingLayer.h"


USING_NS_CC;


AppDelegate::AppDelegate()

{

}


AppDelegate::~AppDelegate()

{

}


bool AppDelegate::applicationDidFinishLaunching()

{

    // initialize director

    CCDirector *pDirector = CCDirector::sharedDirector();

    pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());


    // turn on display FPS

    pDirector->setDisplayStats(false);


    // 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 = LoadingLayer::scene();


    // run

    pDirector->runWithScene(pScene);

    return true;

}


// This function will be called when the app is inactive. When comes a phone call,it's be invoked too

void AppDelegate::applicationDidEnterBackground()

{

    CCDirector::sharedDirector()->stopAnimation();


}


// this function will be called when the app is active again

void AppDelegate::applicationWillEnterForeground()

{

    CCDirector::sharedDirector()->startAnimation();


}

 









LoadingLayer.h


#ifndef _LoadingLayer_

#define _LoadingLayer_


#include "cocos2d.h"


using namespace cocos2d;


class LoadingLayer:public cocos2d::CCLayer

{

public:

virtual bool init();


static cocos2d::CCScene* scene();


CREATE_FUNC(LoadingLayer);


//이후 변수와 메서드 추가 선언


CCSize winSize;


bool isLoading;

bool imagesLoaded;


CCSprite *defaultImage;

CCSprite *main_bkgrnd;

CCSprite *tapToCont;

CCSprite *loading;


void spritesLoaded();

void tick(float dt);

virtual void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent* event);

};


#endif





LoadingLayer.cpp


#include "LoadingLayer.h"

#include "MainMenuLayer.h"


CCScene* LoadingLayer::scene()

{

    CCScene *scene = CCScene::create();

    

    LoadingLayer *layer = LoadingLayer::create();

    

    // 960 x 640

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    if (winSize.width >= 960) {

        layer->setScale(2.0);

        layer->setAnchorPoint(ccp(0.0, 0.0));

    }


    scene->addChild(layer);

    

    return scene;

}


bool LoadingLayer::init()

{

    if ( !CCLayer::init() )

    {

        return false;

    }

    

    /////////////////////////////

    

    // 변수 초기화

    isLoading = true;

    imagesLoaded = false;

    // 터치 활성화

    this->setTouchEnabled(true);


    // 화면 사이즈 구하기

    winSize = CCSizeMake(480, 320);


    // 디폴트 이미지 세로형 화면에 추가하기

    defaultImage = CCSprite::create("Images/loading_bg.png");

    defaultImage->setPosition(ccp(winSize.width/2, winSize.height/2));

    this->addChild(defaultImage);


LoadingLayer::spritesLoaded();

    // 주기적으로 상태체크

    this->schedule(schedule_selector(LoadingLayer::tick));

  

    return true;

}


void LoadingLayer::spritesLoaded()

{

CCLog("11");

    // 메인 백그라운드 이미지 추가

    main_bkgrnd = CCSprite::create("Images/loading_bg.png");

    main_bkgrnd->setPosition( ccp(winSize.width/2, winSize.height/2) );

    this->addChild(main_bkgrnd);

    

    // "Loading..." 글자 이미지 추가

    loading = CCSprite::create("Images/loading_tx.png");

    loading->setPosition( ccp(350,50));

    this->addChild(loading);


    

    // "Loading..." 글자 이미지 깜박이게 애니메이션

    CCFiniteTimeAction* loadingSeqAct = CCSequence::create(CCFadeOut::create(1.0f),

                                                           CCFadeIn::create(1.0f),

                                                           NULL);

    CCAction* rep2 = CCRepeatForever::create((CCActionInterval*)loadingSeqAct);

    loading->runAction(rep2);


    

    // 시작할 때 로딩한 디폴트 이미지를 지운다. (메모리 절약)

    this->removeChild(defaultImage, true);

    

    

    // 이미지가 다 로드되었음을 표시

    imagesLoaded = true;


}


void LoadingLayer::tick(float dt)

{

    

    // 이미지가 다 로드됨

    if (imagesLoaded && isLoading) {

        

        isLoading = false;

        

        // "로딩중 이미지"를 삭제. (메모리 절약)

        this->removeChild(loading, true);

        

        // continue 이미지 추가

        tapToCont = CCSprite::create("Images/continue_tx.png");

        tapToCont->setPosition( ccp(350,50 ));

        this->addChild(tapToCont);

       

        // continue 깜박거림

        // 로딩중 자리에서 대신 나오며 다음 신으로 갈 수 있도록 안내 표시.

        CCFiniteTimeAction* loadingSeqAct = CCSequence::create(CCFadeOut::create(1.0f),

                                                               CCFadeIn::create(1.0f),

                                                               NULL);

        CCAction* rep2 = CCRepeatForever::create((CCActionInterval*)loadingSeqAct);

        tapToCont->runAction(rep2);

    }

    

}


void LoadingLayer::ccTouchesEnded(CCSet *pTouches, CCEvent* event)

{

    if (!isLoading) {

        // 클릭하면 메인메뉴 신으로 이동

       CCScene* pScene = MainMenuLayer::scene();

        CCDirector::sharedDirector()->replaceScene( CCTransitionProgressRadialCW::create(0.5f, pScene) );

    }

}











MainMenuLayer.h


#ifndef __MainMenuLayer__H__

#define __MainMenuLayer__H__


#include "cocos2d.h"


using namespace cocos2d;


class MainMenuLayer : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();



    CREATE_FUNC(MainMenuLayer);


void MainMenuLayer::newGameStart(CCObject* sender);



};

#endif  // __MainMenuLayer__H__





MainMenuLayer.cpp


#include "MainMenuLayer.h"

#include "StageSelect.h"


CCScene* MainMenuLayer::scene()

{

    CCScene *scene = CCScene::create();

    

    MainMenuLayer *layer = MainMenuLayer::create();

    

    // 960 x 640

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    if (winSize.width >= 960) {

        layer->setScale(2.0);

        layer->setAnchorPoint(ccp(0.0, 0.0));

    }


    scene->addChild(layer);

    

    return scene;

}


bool MainMenuLayer::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(255,255,255,255)) )

    {

        return false;

    }

    

    /////////////////////////////

CCSize winSize=CCSizeMake(480, 320);


CCMenuItemFont *newGame=CCMenuItemFont::create("newGame", this, menu_selector(MainMenuLayer::newGameStart));

newGame->setColor(ccc3(0,0,0));

CCMenu* menu=CCMenu::create(newGame,NULL);

menu->setPosition(ccp(winSize.width/2, winSize.height/2));

this->addChild(menu);


    return true;

}


void MainMenuLayer::newGameStart(CCObject* sender)

{

CCScene* pScene=StageSelect::scene();

CCDirector::sharedDirector()->replaceScene(pScene);



}









●StageSelect.h


#ifndef __StageSelect__H__

#define __StageSelect__H__


#include "cocos2d.h"


using namespace cocos2d;


class StageSelect : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();


    CREATE_FUNC(StageSelect);

void StageSelect::doClick(CCObject* pSender);

void StageSelect::doClickX(CCObject* pSender);

bool stage2;

};

#endif  // __StageSelect__H__




●StageSelect.cpp


#include "StageSelect.h"

#include "MainMenuLayer.h"

#include "StageIdx.h"

#include "Stage1Layer.h"

#include "Stage2Layer.h"



CCScene* StageSelect::scene()

{

    CCScene *scene = CCScene::create();

    

    StageSelect *layer = StageSelect::create();

    

    // 960 x 640

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    if (winSize.width >= 960) {

        layer->setScale(2.0);

        layer->setAnchorPoint(ccp(0.0, 0.0));

    }


    scene->addChild(layer);

    

    return scene;

}


bool StageSelect::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(255,255,255,255)) )

    {

        return false;

    }

    

    /////////////////////////////


stage2 = StageIdx::getInstance()->getStage2Bool();

//stage1

CCMenuItemFont *item1=CCMenuItemFont::create("Stage1 O", this, menu_selector(StageSelect::doClick ));

item1->setColor(ccc3(0,0,0));


//stage2

std::string a;

if(stage2)

{

a="Stage2 O ";

}else{

a="String2 X ";

}

CCMenuItemFont *item2=CCMenuItemFont::create(a.c_str(), this, menu_selector(StageSelect::doClick ));

item2->setColor(ccc3(0,0,0));

/*

//stage2

if(stage2)

{

CCMenuItemFont *item2=CCMenuItemFont::create("Stage2 O", this, menu_selector(StageSelect::doClick ));

item2->setColor(ccc3(0,0,0));

}else{

CCMenuItemFont *item2=CCMenuItemFont::create("Stage2 X", this, menu_selector(StageSelect::doClickX ));

item2->setColor(ccc3(0,0,0));

}

*/

//stage3_MainMenu

CCMenuItemFont *item3=CCMenuItemFont::create("Menu", this, menu_selector(StageSelect::doClick ));

item3->setColor(ccc3(0,0,0));

CCMenu* pMenu=CCMenu::create(item1, item2, item3, NULL);

item1->setTag(1);

item2->setTag(2);

item3->setTag(3);


pMenu->alignItemsVertically();

this->addChild(pMenu);

//bool값 테스트

if(stage2)

{

CCLog("Stage2 O 11");

}else{

CCLog("Stage2 X  11111");

}


    return true;

}

//bool 값 


void StageSelect::doClick(CCObject* pSender){


//bool값 테스트

if(stage2)

{

CCLog("Stage2 O 2222");

}else{

CCLog("Stage2 X  2222");

}


CCMenuItem *titem=(CCMenuItem*)pSender;

int i=titem->getTag();


//bool 테스트

if(stage2)

{

CCLog("Stage2 O 3333");

}else{

CCLog("Stage2 X  3333");

}


switch(i){

case 1:

{

CCScene* pScenes=Stage1Layer::scene();

CCDirector::sharedDirector()->replaceScene(pScenes);

break;

}

case 2:

{

if(stage2){

CCScene* pScenes=Stage2Layer::scene();

CCDirector::sharedDirector()->replaceScene(pScenes);

CCLog("stage2 o rrrr");

break;


}else{

CCLog("stage2 x rrrr");

break;

}

}


case 3:

{

CCScene* pScene=MainMenuLayer::scene();

CCDirector::sharedDirector()->replaceScene(pScene);

break;

}


}//switch end




}


void StageSelect::doClickX(CCObject* pSender){


}











Posted by -현's-

댓글을 달아 주세요


●터치하면 캐릭터가 점프하고 장애물을 피하는 게임이다. 장애물에 충돌하면 패배화면으로 넘어간다. 코인에 충돌하면 스코어가 오른다.







●구조






●파일, 리소스 목록








●파일 목록


AppDelegate


LoadingLayer - 로딩 화면


MainMenuLayer - 메인 메뉴 화면


StageSelect - 스테이지 선택 화면


Stage1Layer - 스테이지1 


Stage2Layer - 스테이지2


StageIdx - 스테이지1을 깨야 스테이지2가 선택되도록 처리하기 위한 싱글톤 클래스를 구현


WinLayer - 승리화면


LoseLayer - 패배화면







●동영상










Posted by -현's-

댓글을 달아 주세요


●CCUserDefault

- 환경설정이나 점수등을 저장하는 등 데이터를 저장할 때 사용한다.

ios의 NSUserDefault, 안드로이드의 SharedPreferences와 비슷하다.




●String형 저장,  불러오기

- 저장

CCUserDefault::sharedUserDefault()->setStringForKey("string", "aa");     //(이름, 값)


- 불러오기

std::string s = CCUserDefault::sharedUserDefault()->getStringForKey("string");




●Interger형 저장, 불러오기

- 저장

CCUserDefault::sharedUserDefault()->setIntegerForKey("integer", 1);


- 불러오기

int i = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer");




●Float형 저장, 불러오기

- 저장

CCUserDefault::sharedUserDefault()->setFloatForKey("float", 1.2f);


- 불러오기

float f = CCUserDefault::sharedUserDefault()->getFloatForKey("float");




●Double형 저장, 불러오기

- 저장

CCUserDefault::sharedUserDefault()->setDoubletForKey("double", 1.2);


- 불러오기

double d = CCUserDefault::sharedUserDefault()->getDoubleForKey("double");




●Bool형 저장, 불러오기

- 저장

CCUserDefault::sharedUserDefault()->setBooltForKey("bool", true);


- 불러오기

Bool b = CCUserDefault::sharedUserDefault()->getBoolForKey("bool");





●예제


- HelloWorldScene.h



#ifndef __HELLOWORLD_SCENE_H__

#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"


class HelloWorld : public cocos2d::CCLayerColor

{

public:

    virtual bool init();


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(HelloWorld);



};


#endif // __HELLOWORLD_SCENE_H__




- HelloWorldScene.cpp


#include "HelloWorldScene.h"


using namespace cocos2d;


CCScene* HelloWorld::scene()

{

    CCScene *scene = CCScene::create();

    

    HelloWorld *layer = HelloWorld::create();


    scene->addChild(layer);


    return scene;

}


bool HelloWorld::init()

{

    if ( !CCLayerColor::initWithColor(ccc4(255, 255, 255, 255)) )

    {

        return false;

    }


    /////////////////////////////


CCUserDefault::sharedUserDefault()->setStringForKey("string", "value1");

CCUserDefault::sharedUserDefault()->setFloatForKey("float", 1.1f);

CCUserDefault::sharedUserDefault()->setIntegerForKey("integer", 1);

CCUserDefault::sharedUserDefault()->setDoubleForKey("double", 5.5);

CCUserDefault::sharedUserDefault()->setBoolForKey("bool", "true");


CCUserDefault::sharedUserDefault()->flush();


////////////////////////////

std::string s = CCUserDefault::sharedUserDefault()->getStringForKey("string");

CCLog(s.c_str());

int i = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer");

CCLog("%d",i);

float f = CCUserDefault::sharedUserDefault()->getFloatForKey("float");

CCLog("%f",f);

double d = CCUserDefault::sharedUserDefault()->getDoubleForKey("double");

CCLog("%f",f);

bool b = CCUserDefault::sharedUserDefault()->getBoolForKey("bool");

if(b)

{

CCLog("true");

}else

{

CCLog("false");

}


    return true;

}









'프로그래밍 > cocos2d-x' 카테고리의 다른 글

cocos2d-x warning error C2360  (1) 2013.06.03
cocos2d-x 패럴렉스노드(ParallaxNode)  (0) 2013.06.02
cocos2d-x CCUserDefault  (0) 2013.06.01
cocos2d-x 스케줄  (0) 2013.06.01
cocos2d-x 터치(Touch)  (0) 2013.06.01
cocos2d-x 심플오디오엔진(SimpleAudioEngine)  (0) 2013.05.31
Posted by -현's-

댓글을 달아 주세요


●장면 추가,삭제,교체


- HelloWorldScene.h


#ifndef __HELLOWORLD_SCENE_H__

#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"


#include "Box2D/Box2D.h"


#include "SimpleAudioEngine.h"


class HelloWorld : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(HelloWorld);

void doPushScene(CCObject* pSender);

void doReplaceScene(CCObject* pSender);

};


#endif  // __HELLOWORLD_SCENE_H__




- HelloWorldScene.cpp


#include "HelloWorldScene.h"

#include "TestScene1.h"

#include "TestScene2.h"


using namespace cocos2d;


CCScene* HelloWorld::scene()

{

CCScene *scene=CCScene::create();


HelloWorld *layer=HelloWorld::create();

scene->addChild(layer);


return scene;

}


// on "init" you need to initialize your instance

bool HelloWorld::init()

{

if(!CCLayerColor::initWithColor(ccc4(255,255,255,255)))

{

return false;

}


///////////////////////


//메뉴 아이템 생성 및 초기화

CCMenuItemFont* pMenuItem1=CCMenuItemFont::create(

"pushScene", 

this, 

menu_selector(HelloWorld::doPushScene));

pMenuItem1->setColor(ccc3(0,0,0));

CCMenuItemFont* pMenuItem2=CCMenuItemFont::create(

"replaceScene", 

this, 

menu_selector(HelloWorld::doReplaceScene));

pMenuItem2->setColor(ccc3(0,0,0));

//메뉴 생성

CCMenu* pMenu=CCMenu::create(pMenuItem1,pMenuItem2, NULL);

//메뉴 위치 지정

pMenu->setPosition(ccp(240, 50));

//메뉴 정렬

pMenu->alignItemsVertically();

//레이어에 메뉴 객체 추가

this->addChild(pMenu);

return true;

}


//doPushScene 메서드 정의

void HelloWorld::doPushScene(CCObject* pSender)

{

CCScene* pScene=TestScene1::scene(); 

CCDirector::sharedDirector()->pushScene(pScene);  //기존장면 두고 새장면 올리기


}

//doReplaceScene

void HelloWorld::doReplaceScene(CCObject* pSender)

{

CCScene* pScene=TestScene2::scene();

CCDirector::sharedDirector()->replaceScene(pScene);//기존장면 없애고 새장면 교체


}





- TestScene1.h


#ifndef __TestScene1_H__

#define __TestScene1_H__


#include "cocos2d.h"

#include "Box2D/Box2D.h"

#include "SimpleAudioEngine.h"


class TestScene1 : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(TestScene1);


void doClose(CCObject* pSender);

};


#endif  // __HELLOWORLD_SCENE_H__





- TestScene1.cpp


#include "TestScene1.h"

using namespace cocos2d;


CCScene* TestScene1::scene()

{

CCScene *scene=CCScene::create();


TestScene1 *layer=TestScene1::create();

scene->addChild(layer);


return scene;

}


// on "init" you need to initialize your instance

bool TestScene1::init()

{

if(!CCLayerColor::initWithColor(ccc4(0,255,0,255)))

{

return false;

}


//////////////////////


//메뉴 아이템 생성 및 초기화

CCMenuItemFont* Item1=CCMenuItemFont::create(

"Close", 

this, 

menu_selector(TestScene1::doClose));

Item1->setColor(ccc3(0,0,0));

//메뉴 생성

CCMenu* pMenu=CCMenu::create(Item1, NULL);

//메뉴 위치 지정

pMenu->setPosition(ccp(240, 50));

//레이어에 메뉴 객체 추가

this->addChild(pMenu); 

return true;

}


void TestScene1::doClose(CCObject* pSender)

{

CCDirector::sharedDirector()->popScene();   //pushScene으로 연 장면 닫기

}





- TestScene2.h


#ifndef __TestScene2_H__

#define __TestScene2_H__


#include "cocos2d.h"


#include "Box2D/Box2D.h"


#include "SimpleAudioEngine.h"


class TestScene2 : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(TestScene2);

void doClose(CCObject* pSender);

};


#endif  // __HELLOWORLD_SCENE_H__




- TestScene2.cpp


#include "TestScene2.h"

#include "HelloWorldScene.h"


using namespace cocos2d;


CCScene* TestScene2::scene()

{

CCScene *scene=CCScene::create();


TestScene2 *layer=TestScene2::create();

scene->addChild(layer);


return scene;

}


// on "init" you need to initialize your instance

bool TestScene2::init()

{

if(!CCLayerColor::initWithColor(ccc4(255,255,0,255)))

{

return false;

}


///////////////////////

//메뉴 아이템 생성 및 초기화

CCMenuItemFont* Item1=CCMenuItemFont::create(

"Close Scene", 

this, 

menu_selector(TestScene2::doClose));

Item1->setColor(ccc3(0,0,0));

//메뉴 생성

CCMenu* pMenu=CCMenu::create(Item1, NULL);

//메뉴 위치 지정

pMenu->setPosition(ccp(240, 50));


//레이어에 메뉴 객체 추가

this->addChild(pMenu);

return true;

}


void TestScene2::doClose(CCObject* pSender)

{

CCScene* pScene=HelloWorld::scene();                     //장면을 만들고

CCDirector::sharedDirector()->replaceScene(pScene);   //교체한다


}


 















'프로그래밍 > cocos2d-x' 카테고리의 다른 글

cocos2d-x 심플오디오엔진(SimpleAudioEngine)  (0) 2013.05.31
cocos2d-x 애니메이션  (0) 2013.05.31
cocos2d-x 트랜지션(Transition) 추가,삭제,교체  (0) 2013.05.30
cocos2d-x 액션3  (0) 2013.05.29
cocos2d-x 액션2  (0) 2013.05.28
cocos2d-x 액션1  (0) 2013.05.28
Posted by -현's-

댓글을 달아 주세요



이즈 액션(Ease Action)

- 전체 액션시간은 수정하지 않고 내부의 액션 속도를 조절한다.


CCEaseIn - 액션의 끝이 빨라진다.

CCEaseOut - 액션의 처음이 빨라졌다가 끝이 느려진다.

CCEaseInOut - 액션의 처음이 느렸다가 중간에 빨라지고 끝에서 느려진다.



void HelloWorld::doAction(CCObject* pSender) 

{

//액션 정의

CCActionInterval* move=CCMoveBy::create(2,ccp(100,0));


//빨라지기

CCActionInterval* move_ease_in=CCEaseIn::create(move, 2);

//느려지기

CCActionInterval* move_ease_out=CCEaseOut::create(move, 2);

//빨라졌다 느려지기

CCActionInterval* move_ease_inout=CCEaseInOut::create(move, 2);

pMan->runAction(move_ease_in);

//pMan->runAction(move_ease_out);

//pMan->runAction(move_ease_inout);

}









●콜백 액션

- 액션에서 메서드를 호출하는 것이다. 

CCCallFunc 액션에서 메서드를 호출하게 한다. CCCallFuncN은 파라미터로 노드를 삽입한다. CCCallFuncND는 노드와 포인터형 데이터를 파리미터로 사용한다. 액션이 끝나고 어떤 동작을 수행해야 할 때 사용한다.



- HelloWorldScene.h


#ifndef __HELLOWORLD_SCENE_H__

#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"


#include "Box2D/Box2D.h"


#include "SimpleAudioEngine.h"


class HelloWorld : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(HelloWorld);


cocos2d::CCSprite* pMan;

void doAction(CCObject* pSender);

void callback1();

void callback2(CCNode* sender);

void callback3(CCNode* sender, void* data);

};


#endif  // __HELLOWORLD_SCENE_H__



- HelloWorldScene.cpp


#include "HelloWorldScene.h"


using namespace cocos2d;


CCScene* HelloWorld::scene()

{

CCScene *scene=CCScene::create();


HelloWorld *layer=HelloWorld::create();

scene->addChild(layer);


return scene;

}


// on "init" you need to initialize your instance

bool HelloWorld::init()

{

if(!CCLayerColor::initWithColor(ccc4(255,255,255,255)))

{

return false;

}


///////////////////////


//메뉴 아이템 생성 및 초기화

CCMenuItemFont* pMenuItem1=CCMenuItemFont::create(

"Action", 

this, 

menu_selector(HelloWorld::doAction));

pMenuItem1->setColor(ccc3(0,0,0));

//메뉴 생성

CCMenu* pMenu=CCMenu::create(pMenuItem1, NULL);

//메뉴 위치 지정

pMenu->setPosition(ccp(240, 50));


//레이어에 메뉴 객체 추가

this->addChild(pMenu);



//Grossini 스프라이트 추가

pMan=CCSprite::create("Images/grossini.png");

pMan->setPosition(ccp(50,200));

this->addChild(pMan);

return true;

}


//doAction 메서드 정의

void HelloWorld::doAction(CCObject* pSender)

{

//Grossini 스프라이트 제거

pMan->removeFromParentAndCleanup(true);


//태그로 레이블 제거

this->removeChildByTag(1, true);

this->removeChildByTag(2, true);

this->removeChildByTag(3, true);


//Grossini 스프라이트 추가

pMan->CCSprite::create("Images/grossini.png");

pMan->setPosition(ccp(50,160));


this->addChild(false);

pMan->setVisible(false);


CCFiniteTimeAction* action=CCSequence::create(

CCPlace::create(ccp(200,200)),

CCShow::create(),

CCMoveBy::create(1, ccp(200,0)),

CCCallFunc::create(this, callfunc_selector(HelloWorld::callback1)),

     CCCallFuncN::create(this, callfuncN_selector(HelloWorld::callback2)),

     CCCallFuncND::create(this, callfuncND_selector(HelloWorld::callback3), (void*)0xbebabeba),

NULL);

pMan->runAction(action);

}


#pragma mark -

#pragma mark Callback Functions


void HelloWorld::callback1(){

CCLabelTTF *label=CCLabelTTF::create("callback 1 called", "Marker Felt", 16);

label->setPosition(ccp(120, 160));

label->setColor(ccBLACK);

label->setTag(1);

addChild(label);

}


void HelloWorld::callback2(CCNode* sender){

CCLabelTTF *label=CCLabelTTF::create("callback 2 called", "Marker Felt", 16);

label->setPosition(ccp(120, 160));

label->setColor(ccBLACK);

label->setTag(2);

addChild(label);

}


void HelloWorld::callback3(CCNode* sender, void* data){

CCLabelTTF *label=CCLabelTTF::create("callback 3 called", "Marker Felt", 16);

label->setPosition(ccp(120, 160));

label->setColor(ccBLACK);

label->setTag(3);

addChild(label);

}










'프로그래밍 > cocos2d-x' 카테고리의 다른 글

cocos2d-x 애니메이션  (0) 2013.05.31
cocos2d-x 트랜지션(Transition) 추가,삭제,교체  (0) 2013.05.30
cocos2d-x 액션3  (0) 2013.05.29
cocos2d-x 액션2  (0) 2013.05.28
cocos2d-x 액션1  (0) 2013.05.28
cocos2d-x 메뉴  (0) 2013.04.27
Posted by -현's-

댓글을 달아 주세요


●CCSequence

- 액션의 순서를 정하고 순차적으로 실행한다.


void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

CCActionInterval* action1=CCMoveTo::create(2,ccp(100,200));

CCActionInterval* action2=CCRotateBy::create(2,90);

CCActionInterval* action3=CCScaleTo::create(2, 2.0);


CCFiniteTimeAction* seq=CCSequence::create(action1, action2, action3, NULL);


pMan->runAction(seq);

}

 








●CCSpawn

- 등록된 모든 액션을 동시에 시행한다.


void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

CCActionInterval* action1=CCMoveTo::create(2,ccp(100,200));

CCActionInterval* action2=CCRotateBy::create(2,90);

CCActionInterval* action3=CCScaleTo::create(2, 2.0);


CCFiniteTimeAction* seq=CCSpawn::create(action1, action2, action3, NULL);


pMan->runAction(seq);








●CCDelayTime

- 스퀀스(Sequence)로 액션을 등록 떄 일정시간 지연 효과를 준다.


//doAction 메서드 정의

void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

CCActionInterval* action1=CCMoveTo::create(2,ccp(100,200));

CCActionInterval* action2=CCRotateBy::create(2,90);

CCActionInterval* action3=CCScaleTo::create(2, 2.0);


CCFiniteTimeAction* seq=CCSequence::create(action1, CCDelayTime::create(2), action2, action3, NULL);


pMan->runAction(seq);








●CCRepeat, CCRepeatForever

- CCRepeat는 지정한 횟수만큼 반복시키고, CCRepeatForever는 무한 반복시킨다.


void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

CCActionInterval* action1=CCMoveBy::create(2,ccp(100,0));

CCActionInterval* action2=CCRotateBy::create(2,90);

CCActionInterval* action3=CCScaleBy::create(2, 2.0);


CCFiniteTimeAction* seq=CCSequence::create(action1,CCDelayTime::create(2), action2, action3, NULL);


CCActionInterval* rep=CCRepeat::create(seq, 3);  // 무한반복하려면 CCRepeatForever::create(seq);


pMan->runAction(rep);

}










'프로그래밍 > cocos2d-x' 카테고리의 다른 글

cocos2d-x 트랜지션(Transition) 추가,삭제,교체  (0) 2013.05.30
cocos2d-x 액션3  (0) 2013.05.29
cocos2d-x 액션2  (0) 2013.05.28
cocos2d-x 액션1  (0) 2013.05.28
cocos2d-x 메뉴  (0) 2013.04.27
cocos2d-x 스프라이트(sprite)  (0) 2013.04.25
Posted by -현's-

댓글을 달아 주세요

 

 

●액션

- 많은 액션은  By와 To로 나뉘는데 By는 지정한 값만큼 변하는 것이고, To는 지정한 값으로 변하는 것이다.

- 위치관련 - CCMoveBy, CCMoveTo, CCJumpBy, CCJumpTo, CCBezierBy, CCBezierTo, CCPlace

- 크기관련 - CCScaleBy, CCScaleTo

- 회전관련 - CCRotateBy, CCRotateTo

- 가시성 - CCShow, CCHide, CCBlink, CCToggleVisibility

- 투명도 - CCFadeIn, CCFadeOut, CCFadeTo

- 색관련 - CCTintBy, CCTintTo

 

 

 

 

 

●액션 기본 예제 - HelloWorldScene.cpp의 doAction함수안에 여러가지 액션 함수를 넣어 액션 예제를 확인한다.


- HelloWorldScene.h


#ifndef __HELLOWORLD_SCENE_H__


#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"


#include "Box2D/Box2D.h"


#include "SimpleAudioEngine.h"


class HelloWorld : public cocos2d::CCLayerColor

{

public:

    virtual bool init();  


    static cocos2d::CCScene* scene();

    

    CREATE_FUNC(HelloWorld);


cocos2d::CCSprite* pMan;

void doAction(CCObject* pSender);

void doActionReverse(CCObject* pSender);

void doActionReset(CCObject* pSender);


};


#endif  // __HELLOWORLD_SCENE_H__


 



- HelloWorldScene.cpp


 #include "HelloWorldScene.h"


using namespace cocos2d;


CCScene* HelloWorld::scene()

{

CCScene *scene=CCScene::create();


HelloWorld *layer=HelloWorld::create();

scene->addChild(layer);


return scene;

}


// on "init" you need to initialize your instance

bool HelloWorld::init()

{

if(!CCLayerColor::initWithColor(ccc4(255,255,255,255)))

{

return false;

}


///////////////////////


//메뉴 아이템 생성 및 초기화

CCMenuItemFont* pMenuItem1=CCMenuItemFont::create(

"Action", this, menu_selector(HelloWorld::doAction));

pMenuItem1->setColor(ccc3(0,0,0));


CCMenuItemFont* pMenuItem2=CCMenuItemFont::create(

"ActionReverse", this, menu_selector(HelloWorld::doActionReverse));

pMenuItem2->setColor(ccc3(0,0,0));


CCMenuItemFont* pMenuItem3=CCMenuItemFont::create(

"ActionReset", this, menu_selector(HelloWorld::doActionReset));

pMenuItem3->setColor(ccc3(0,0,0));


//메뉴 생성

CCMenu* pMenu=CCMenu::create(pMenuItem1, pMenuItem2, pMenuItem3, NULL);


//메뉴 배치

pMenu->alignItemsHorizontally();


//메뉴 위치 지정

pMenu->setPosition(ccp(240, 50));


//레이어에 메뉴 객체 추가

this->addChild(pMenu);



//Grossini 스프라이트 추가

pMan=CCSprite::create("Images/grossini.png");

pMan->setPosition(ccp(50,200));

this->addChild(pMan);

return true;

}


//doAction 메서드 정의

void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

}


//doActionReverse 메서드 정의

void HelloWorld::doActionReverse(CCObject* pSender)

{

//액션 리버스 정의

}


//doActionReset 메서드 정의

void HelloWorld::doActionReset(CCObject* pSender)

{

//좌표 초기화

pMan->setPosition(ccp(50, 200));


//회전 초기화

pMan->setRotation(0.0);


//크기 초기화

pMan->setScale(1.0);

}

 

 

 



 

 

 



 

 

●MoveBy

- ccp(x, y) 해당 값만큼 이동한다.



 //doAction 메서드 정의

 void HelloWorld::doAction(CCObject* pSender)

 {

//액션 정의

CCActionInterval* myAction=CCMoveBy::create(2, ccp(400, 0));

pMan->runAction(myAction);

 }


 //doActionReverse 메서드 정의

 void HelloWorld::doActionReverse(CCObject* pSender)

 {

//액션 리버스 정의

CCActionInterval* myAction=CCMoveBy::create(2, ccp(400,0));

CCActionInterval* myActionBack=myAction->reverse();

pMan->runAction(myActionBack);

 }



 

 

 

 


JumpBy

- (2, ccp(400,0), 50, 3) - cpp(400,0) 만큼 이동하면서 50 높이만큼 3번 점프한다.


 //doAction 메서드 정의 

 void HelloWorld::doAction(CCObject* pSender)

 {

//액션 정으

CCActionInterval* myAction=CCJumpBy::create(2, ccp(400, 0), 50, 3);

pMan->runAction(myAction);

 }


 //doActionReverse 메서드 정의

 void HelloWorld::doActionReverse(CCObject* pSender)

 {

//액션 리버스 정의

CCActionInterval* myAction=CCJumpBy::create(2, ccp(400 ,0), 50, 3);

CCActionInterval* myActionBack=myAction->reverse();

pMan->runAction(myActionBack);

 } 


 



 

 


●CCBezierBy

- 해당값만큼 곡선으로 이동한다.



void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

ccBezierConfig bezier;

bezier.controlPoint_1=ccp(150, 150);

bezier.controlPoint_2=ccp(250, -150);

bezier.endPosition=ccp(350,0);


CCActionInterval* myAction=CCBezierBy::create(3, bezier);


pMan->runAction(myAction);

}


//doActionReverse 메서드 정의

void HelloWorld::doActionReverse(CCObject* pSender)

{

//액션 리버스 정의

ccBezierConfig bezier;

bezier.controlPoint_1=ccp(150, 150);

bezier.controlPoint_2=ccp(250, -150);

bezier.endPosition=ccp(350,0);


CCActionInterval* myAction=CCBezierBy::create(3, bezier);

CCActionInterval* myActionBack=myAction->reverse();


pMan->runAction(myActionBack);


}









CCPlace

- 해당 위치로 즉시 이동한다.



 void HelloWorld::doAction(CCObject* pSender)

{

//액션 정의

CCFiniteTimeAction* myAction=CCPlace::create(ccp(300,200));


pMan->runAction(myAction);



}










●CCScaleBy

- 해당 수치만큼 크기를 조절한다.


void HelloWorld::doAction(CCObject* pSender)

{

//액션 액션

CCActionInterval* myAction=CCScaleBy::create(2, 2.0);   //create(시간, 배수)


pMan->runAction(myAction);

}



//doActionReverse 메서드 정의

void HelloWorld::doActionReverse(CCObject* pSender)

{

//액션 리버스 정의

CCActionInterval* myAction=CCScaleBy::create(2, 2.0);

CCActionInterval* myActionBack=myAction->reverse();


pMan->runAction(myActionBack);


}









CCRotateBy

- 해당 각도만큼 회전한다.


//doAction 메서드 정의

void HelloWorld::doAction(CCObject* pSender)

{

//액션 액션

CCActionInterval* myAction=CCRotateBy::create(2, 90);


pMan->runAction(myAction);

}



//doActionReverse 메서드 정의

void HelloWorld::doActionReverse(CCObject* pSender)

{

//액션 리버스 정의

CCActionInterval* myAction=CCRotateBy::create(2, 90);

CCActionInterval* myActionBack=myAction->reverse();


pMan->runAction(myActionBack);


}








'프로그래밍 > cocos2d-x' 카테고리의 다른 글

cocos2d-x 액션3  (0) 2013.05.29
cocos2d-x 액션2  (0) 2013.05.28
cocos2d-x 액션1  (0) 2013.05.28
cocos2d-x 메뉴  (0) 2013.04.27
cocos2d-x 스프라이트(sprite)  (0) 2013.04.25
cocos2d-x CCLabelTTF  (0) 2013.04.22
Posted by -현's-

댓글을 달아 주세요



●메뉴 사용하기

- cpp에 메서드를 추가하려면 헤더파일에도 선언을 추가해야한다.





- HelloWorldScene.cpp dp  다음과 같이 입력해준다.










●메뉴 아이템에서 태그 사용하기

- 메뉴 아이템에 태그를 사용하면 같은 메서드에서 어떤 메뉴 아이템이 선택되었는지 구분할 수 있다.

- 헤더파일에 cpp에서 사용할 메서드를 선언해준다.







'프로그래밍 > cocos2d-x' 카테고리의 다른 글

cocos2d-x 액션2  (0) 2013.05.28
cocos2d-x 액션1  (0) 2013.05.28
cocos2d-x 메뉴  (0) 2013.04.27
cocos2d-x 스프라이트(sprite)  (0) 2013.04.25
cocos2d-x CCLabelTTF  (0) 2013.04.22
cocos2d-x Visual studio 프로젝트 생성할때 스크립트 오류  (0) 2013.04.19
Posted by -현's-

댓글을 달아 주세요