5가지 실전 게임으로 배우는 코코스2d-x(cocos2d-x) 모바일 2D 게임 개발 첫번째 예제.
- Study/Cocos2d-x 3.x
- 2014. 8. 8. 01:24
에이콘 출판사에서 나온 5가지 실전 게임으로 배우는 코코스2d-x 책을 보려고 하는데 코코스 2d-x버전으로 되있어서 현재 버전에 적용하기 상~당히 힘들다. (3.2 alpha)
그렇다고 딱히 다른 책이 있는 것도 아니고...해서 예제를 처보기로 정했다.
하지만 생각보다 코코스 2.x 와 3.x 가 달라진게 많아서 상~당한 시행착오를 겪었는데 다른 사람들도 이책을 공부하려고 하다가 버전이 안맞아서 짜증날지도 모르니 포스트 하려고 한다.
일단 이 책에 첫번째 예제는 하키게임을 만드는 것입니다. 하키게임이 뭐냐면..
아시죠? ㅎㅎ
스샷이 이 책에서 만든건데 생각보다 완성도 있는 게임이였습니다. 그럼 책에 있는 코드에서 수정해야 되는 부분을 살펴볼까요?
일단 제일 첫번째 부터 수정해야합니다. 책에 보면
CCSize screenSize = pEGLView->getFrameSize();
//set design screen size to the iPad and ExactFit (image is stretched to fill screen
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(768, 1024, kResolutionExactFit);
//if device's screen width is greater than 768, use high definition images
if (screenSize.width > 768) {
CCFileUtils::sharedFileUtils()->setResourceDirectory("hd");
pDirector->setContentScaleFactor(2);
//or else, use standard definition
} else {
CCFileUtils::sharedFileUtils()->setResourceDirectory("sd");
pDirector->setContentScaleFactor(1);
}
위와 같은 코드가 있습니다.
2.x버전을 제가 안해봐서 모르겠는데 대부분 선언할때 CC를 붙이더군요? 근데 3.x 버전을 공부하면서 CC를 붙이는 경우가 거의 없었어요. 그래서 CC를 다 때버렸습니다.
CCSize -> Size 이렇게요.
또 해상도 조절하는 부분도 이렇게 바꿉니다.
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(768, 1024, kResolutionExactFit);
-> glview->setDesignResolutionSize(768, 1024, kResolutionExactFit);
이전 책을 참고해서 바꿔봤습니다.
하나하나 설명하려니까 상당히 기네요 ㅎㅎ 그냥 바뀐 appdeligate.cpp를 첨부하겠습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include "AppDelegate.h" #include "GameLayer.h" #include "SimpleAudioEngine.h" USING_NS_CC; using namespace CocosDenshion; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { glview = GLView::create("My Game"); director->setOpenGLView(glview); } Size screenSize = glview->getFrameSize(); glview->setDesignResolutionSize(768, 1024, kResolutionExactFit); std::vector<std::string> searchPaths; if (screenSize.width > 768) { searchPaths.push_back("hd"); CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths); director->setContentScaleFactor(2); }else{ searchPaths.push_back("sd"); CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths); director->setContentScaleFactor(1); } // turn on display FPS director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object auto scene = GameLayer::createScene(); // run director->runWithScene(scene); 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() { Director::getInstance()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); } |
코코스 3.2Alpha버전에서 새로 만든 프로젝트를 베이스로 만든것입니다.
그 다음은 사운드 효과 부분인데요, 이 책에서는 preloadEffect를 사용해서 사운드를 미리 불러와 앱에 부하를 줄인다고 했는데 3.2부터는 이 기능이 사용되지 않는다고 뜨더라구요. 그래서 그냥 Layer에서 즉석으로 사용하는 방법을 사용했습니다.
헤더에서 따로 선언하지 않고
SimpleAudioEngine::getInstance()->playEffect("hit.wav");
코드를 사용해서 효과음을 사용할 수 있습니다. using namespace CocosDenshion은 하셔야 되요 ^^
전체적으로 수정한 cpp파일과 헤더 파일입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #ifndef __GameLayer_H__ #define __GameLayer_H__ #define GOAL_WIDTH 400 #include "cocos2d.h" #include "GameSprite.h" using namespace cocos2d; class GameLayer : public cocos2d::Layer { public: // there's no 'id' in cpp, so we recommend returning the class instance pointer static cocos2d::Scene* createScene(); GameSprite* _player1; GameSprite* _player2; GameSprite* _ball; CCArray* _players; CCLabelTTF* _player1ScoreLabel; CCLabelTTF* _player2ScoreLabel; Size _screenSize; int _player1Score; int _player2Score; void playerScore(int player); ~GameLayer(); // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); static Scene* scene(); // implement the "static create()" method manually CREATE_FUNC(GameLayer); virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event); virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event); virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event); void update(float delta); }; #endif // __HELLOWORLD_SCENE_H__ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | #include "GameLayer.h" USING_NS_CC; using namespace CocosDenshion; Scene* GameLayer::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = GameLayer::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool GameLayer::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } _player1Score =0; _player2Score =0; _screenSize = Director::getInstance()->getWinSize(); auto court = Sprite::create("court.png"); court->setPosition(Point(_screenSize.width/2,_screenSize.height/2)); this->addChild(court); _player1 = GameSprite::gameSpriteWithFile("mallet.png"); _player2 = GameSprite::gameSpriteWithFile("mallet.png"); _player1->setPosition(Point(_screenSize.width*0.5,_player1->radius()*2)); _player2->setPosition(Point(_screenSize.width*0.5,_screenSize.height-_player1->radius()*2)); this->addChild(_player1); this->addChild(_player2); _ball = GameSprite::gameSpriteWithFile("puck.png"); _ball->setPosition(Point(_screenSize.width/2,_screenSize.height/2)); this->addChild(_ball); _players = CCArray::create(_player1,_player2,NULL); _players->retain(); _player1ScoreLabel = CCLabelTTF::create("0","Arial",60); _player2ScoreLabel = CCLabelTTF::create("0","Arial",60); _player1ScoreLabel->setPosition(Point(_screenSize.width-60,_screenSize.height/2 -80)); _player1ScoreLabel->setRotation(90); _player2ScoreLabel->setPosition(Point(_screenSize.width-60,_screenSize.height/2+80)); _player2ScoreLabel->setRotation(90); this->addChild(_player1ScoreLabel); this->addChild(_player2ScoreLabel); auto listener = EventListenerTouchAllAtOnce::create(); listener->onTouchesBegan=CC_CALLBACK_2(GameLayer::onTouchesBegan, this); listener->onTouchesMoved=CC_CALLBACK_2(GameLayer::onTouchesMoved, this); listener->onTouchesEnded=CC_CALLBACK_2(GameLayer::onTouchesEnded, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener,1); this->scheduleUpdate(); return true; } GameLayer::~GameLayer() { CC_SAFE_DELETE(_players); } void GameLayer::onTouchesBegan(const std::vector<Touch *> &touches, cocos2d::Event *unused_event) { std::vector<Touch *>::const_iterator it = touches.begin(); Touch* touch; Point tap; GameSprite* player; for (int i =0; i<touches.size(); i++) { touch = (Touch*)(*it); if(touch){ tap = touch->getLocation(); for (int p = 0 ; p<2; p++) { player = (GameSprite*) _players->getObjectAtIndex(p); if(player->boundingBox().containsPoint(tap)){ player->setTouch(touch); CCLOG("터치됨 %d",p); } } } it++; } } void GameLayer::onTouchesMoved(const std::vector<Touch *> &touches, cocos2d::Event *unused_event) { std::vector<Touch *>::const_iterator it = touches.begin(); Touch* touch; Point tap; GameSprite* player; for (int i =0; i<touches.size(); i++) { touch = (Touch*)(*it); if(touch){ tap = touch->getLocation(); for (int p = 0 ; p< _players->count(); p++) { player = (GameSprite*)_players->getObjectAtIndex(p); if(player->getTouch() !=NULL && player ->getTouch() ==touch){ Point nextPosition = tap; if (nextPosition.x<player->radius()) nextPosition.x = player->radius(); if (nextPosition.x>_screenSize.width- player->radius()) nextPosition.x = _screenSize.width-player->radius(); if(nextPosition.y<player->radius()) nextPosition.y = player->radius(); if(nextPosition.y > _screenSize.height-player->radius()) nextPosition.y = _screenSize.height-player->radius(); if(player->getPositionY()< _screenSize.height/2){ if (nextPosition.y>_screenSize.height/2 -player->radius()) { nextPosition.y=_screenSize.height/2 -player->radius(); } }else{ if(nextPosition.y<_screenSize.height/2 +player->radius()){ nextPosition.y = _screenSize.height/2+player->radius(); } } player->setNextPosition(nextPosition); player->setVector(Point(tap.x - player->getPositionX(),tap.y-player->getPositionY())); } } } it++; } } void GameLayer::onTouchesEnded(const std::vector<Touch *> &touches, cocos2d::Event *unused_event){ std::vector<Touch *>::const_iterator it = touches.begin(); Touch* touch; Point tap; GameSprite* player; for (int i =0; i<touches.size(); i++) { touch = (Touch*)(*it); if(touch){ tap = touch->getLocation(); for (int p = 0 ; p<2; p++) { player = (GameSprite*) _players->getObjectAtIndex(p); if(player->getTouch() !=NULL && player->getTouch() ==touch){ player->setTouch(NULL); player->setVector(Point(0,0)); } } } it++; } } void GameLayer::update(float delta) { Point ballNextPosition = _ball->getNextPosition(); Point ballVector = _ball->getVector(); //ballVector = ccpMult(ballVector, 0.98); ballNextPosition.x +=ballVector.x; ballNextPosition.y +=ballVector.y; GameSprite* player; Point playerNextPosition; Point playerVector; float squared_radii = pow(_player1->radius() + _ball->radius(),2); for (int p = 0; p<_players->count(); p++) { player = (GameSprite*) _players->getObjectAtIndex(p); playerNextPosition= player->getNextPosition(); playerVector = player->getVector(); float diffx = ballNextPosition.x - player->getPositionX(); float diffy = ballNextPosition.y - player->getPositionY(); float distance1 = pow(diffx, 2) + pow(diffy, 2); float distance2 = pow(_ball->getPositionX()-playerNextPosition.x,2)+ pow(_ball->getPositionY()- playerNextPosition.y,2); if (distance1 <= squared_radii || distance2<=squared_radii) { float mag_ball = pow(ballVector.x, 2) + pow(ballVector.y, 2); float mag_Playeer = pow(playerVector.x, 2)+pow(playerVector.y, 2); float force = sqrt(mag_ball + mag_Playeer); float angle = atan2(diffy,diffx); CCLOG("%f",force); if (force >= 100) { force = 100; } ballVector.x = force *cos(angle); ballVector.y = force*sin(angle); ballNextPosition.x = playerNextPosition.x +(player->radius() +_ball->radius() +force)*cos(angle); ballNextPosition.y = playerNextPosition.y + (player->radius()+ _ball->radius() + force)*sin(angle); SimpleAudioEngine::getInstance()->playEffect("hit.wav"); } } if(ballNextPosition.x<_ball->radius()){ ballNextPosition.x = _ball->radius(); ballVector.x *= -0.8f; SimpleAudioEngine::getInstance()->playEffect("hit.wav"); } if(ballNextPosition.x > _screenSize.width-_ball->radius()){ ballNextPosition.x = _screenSize.width -_ball->radius(); ballVector.x *= -0.8f; SimpleAudioEngine::getInstance()->playEffect("hit.wav"); } if(ballNextPosition.y > _screenSize.height - _ball->radius()){ if (_ball->getPositionX() < _screenSize.width/2 - GOAL_WIDTH/2 || _ball->getPositionX()>_screenSize.width/2 +GOAL_WIDTH/2) { ballNextPosition.y = _screenSize.height - _ball->radius(); ballVector *= -0.8f; SimpleAudioEngine::getInstance()->playEffect("hit.wav"); } } if(ballNextPosition.y < _ball->radius()){ if (_ball->getPositionX() < _screenSize.width/2 - GOAL_WIDTH/2 || _ball->getPositionX()>_screenSize.width/2 +GOAL_WIDTH/2) { ballNextPosition.y = _ball->radius(); ballVector *= -0.8f; SimpleAudioEngine::getInstance()->playEffect("hit.wav"); } } _ball->setVector(ballVector); _ball->setNextPosition(ballNextPosition); if(ballNextPosition.y < -_ball->radius()*2){ this->playerScore(2); } if(ballNextPosition.y > _screenSize.height + _ball->radius()*2){ this->playerScore(1); } _player1->setPosition(_player1->getNextPosition()); _player2->setPosition(_player2->getNextPosition()); _ball->setPosition(_ball->getNextPosition()); } void GameLayer::playerScore(int player) { SimpleAudioEngine::getInstance()->playEffect("score.wav"); _ball->setVector(Point(0,0)); char score_buffer[10]; if (player ==1) { _player1Score++; sprintf(score_buffer, "%i",_player1Score); _player1ScoreLabel->setString(score_buffer); _ball->setNextPosition(Point(_screenSize.width/2,_screenSize.height/2+2*_ball->radius())); }else{ _player2Score++; sprintf(score_buffer, "%i",_player1Score); _player2ScoreLabel->setString(score_buffer); _ball->setNextPosition(Point(_screenSize.width/2,_screenSize.height/2-2*_ball->radius())); } _player1->setPosition(Point(_screenSize.width*0.5,_player1->radius()*2)); _player2->setPosition(Point(_screenSize.width*0.5,_screenSize.height -_player1->radius()*2)); _player1->setTouch(NULL); _player2->setTouch(NULL); } |
눈에 띄는 수정은 터치 이벤트에 관한 설정입니다. 2.x버전에서는 this->setTouch어쩌구를 true로 해서 터치이벤트를 받았지만 3.x 에서는
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan=CC_CALLBACK_2(GameLayer::onTouchesBegan, this);
listener->onTouchesMoved=CC_CALLBACK_2(GameLayer::onTouchesMoved, this);
listener->onTouchesEnded=CC_CALLBACK_2(GameLayer::onTouchesEnded, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener,1);
위와같은 코드를 사용했습니다.
그거 말고는 뭐 거의 비슷하다고 생각되네요.
다음으로 GameSprite.cpp와 .h 는 거의 똑같이 사용했습니다 ^^
제가 하면서 수정할때는 오래걸렸는데 포스팅하려고하니 금방이네요.. 복붙의 힘인가.
다음 예제로 찾아뵙겠습니다~
'Study > Cocos2d-x 3.x' 카테고리의 다른 글
5가지 실전 게임으로 배우는 코코스2d-x(cocos2d-x) 모바일 2D 게임 개발 두번째 예제(2) (2) | 2014.08.26 |
---|---|
5가지 실전 게임으로 배우는 코코스2d-x(cocos2d-x) 모바일 2D 게임 개발 두번째 예제(1) (0) | 2014.08.22 |
cocos2d-x 기본 프로젝트 생성하기 (0) | 2014.08.08 |
cocos2d-x 3.x 사운드, 터치 이벤트 (0) | 2014.08.07 |
화면 조절에 관해서 setDesignResolutionSize (0) | 2014.08.07 |