●좌측 솔루션 탐색기에서 TestCpp을 디버그하면 cocos2d-x에 관한 여러가지 예제를 실행시켜 볼 수 있다.















Posted by -현's-

댓글을 달아 주세요




●게임 중 화면을 정지 버튼을 누르면 일시정지하고 팝업창을 띄운다. 팝업창에서 버튼은 누르면 다시 게임 화면으로 돌아간다. 팝업창을 띄우고 게임상의 액션,스케줄을 멈추고 재시작하기 위해 " 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-

댓글을 달아 주세요


●sprintf

- 메모리에 출력한다.

- sprintf(문자배열명, "출력문자와 자료형(ex.%d)", 입력 데이터);





●예제

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

    }

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



//레이블 생성 및 초기화

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

//레이블 위치 지정

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

//레이블 색 지정

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

//레이블의 투명도 지정

pLabel->setOpacity(100.0);

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

this->addChild(pLabel);


char coinScore[100] = {0};

int score=0;

for(int i=0; i<100;i++){

score++;

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

CCLog("score:%d", score);

pLabel->setString(coinScore);

}



    return 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-

댓글을 달아 주세요


처리되지 않은 예외가 있습니다. 엑세스 위반이 발생했습니다 - 에러

- 메모리 할당이 안 되어 있거나 할당된 수치를 넘어서 데이터가 저장되었을 때 나타난다.






Posted by -현's-

댓글을 달아 주세요


●error2360

- switch문에서 나타난 에러이다. 에러를 해결하려면 switch문 case에 {} 을 사용한다.


ex)

switch(a){

case 1:

     {

             ~~~

      }

case 2:

     {

             ~~~

      }

}








Posted by -현's-

댓글을 달아 주세요

  1.  댓글주소 수정/삭제 댓글쓰기 2013.06.04 01:38

    비밀댓글입니다


●두개이상의 배경 이미지 패럴랙스노드에 추가


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

    }


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

//배경 스프라이트1

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

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

//배경 스프라이트2

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

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(512,0));



CCActionInterval* go = CCMoveBy::create(4, ccp(-512, 0));

CCActionInterval* goBack = go->reverse();

CCFiniteTimeAction* seq = CCSequence::create(go, goBack, NULL);

CCAction* act = CCRepeatForever::create((CCActionInterval*)seq);


voidNode->runAction(act);

this->addChild(voidNode);

    return true;

}









●배경과 스프라이트 이미지 동시에 움직이기


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

    }


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

//배경레이어1

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

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

//배경레이어2

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

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(512,0));



CCActionInterval* go = CCMoveBy::create(4, ccp(-512, 0));

CCActionInterval* goBack = go->reverse();

CCFiniteTimeAction* seq = CCSequence::create(go, goBack, NULL);

CCAction* act = CCRepeatForever::create((CCActionInterval*)seq);


voidNode->runAction(act);

this->addChild(voidNode);


//움직이는 용 추가

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

}

//스프라이트 생성

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

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

this->addChild(dragon);


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

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

dragon->runAction(rep);

    return true;

}









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-

댓글을 달아 주세요