본문 바로가기

cocos2d-x/pyocopang

cocos2d-x 포코팡 류 게임만들기!! - 2 - 기본 화면 구성

다음의 내용들을 통해 게임의 기본 화면을 구성해보려고 합니다.

 - 화면을 세로로 고정
 - 배경화면 이미지 삽입
 - 나무 이미지 삽입
 - 적 이미지 삽입

화면을 세로 또는 가로로 고정하는 방법과 게임 이미지를 원하는 크기와 위치에 배치하도록 하는 방법 등을 알아보겠습니다. 특히 게임 이미지를 제어하는 것은 앞으로 자주 사용할 것 같아서 익숙해지도록 노력해야겠습니다.

- 2 - 기본 화면 구성

일단 뭐든 시작하기 전에 프로젝트를 생성하겠습니다. 저는 포코팡의 표절작이라는 의미에서 '표코팡 프로젝트'라고 지칭하겠습니다. 이전 글을 참조해서 프로젝트를 생성합니다.

프로젝트 생성 방법


1. 화면을 세로로 고정

기본적으로 포코팡과 동일하게 세로화면으로 고정하고 게임을 진행하도록 하겠습니다. 플랫폼 마다 방법이 다른데, 많이 사용하고 있는 ios와 android에 대해 알아보도록 하죠.

1) proj.ios

/proj.ios/RootViewController.mm 의 아래 내용을 수정합니다.

// Override to allow orientations other than the default portrait orientation.
// This method is deprecated on ios6
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return UIInterfaceOrientationIsPortrait( interfaceOrientation );
}

또한 아래와 같이 수정하여 자동회전없이 항상 세로화면을 볼 수 있게 설정합니다.

- (BOOL) shouldAutorotate {
    return NO; 
}


2) proj.android

android에서는 /proj.android/AndroidManifest.xml 파일의 중간 부분을 landscape에서 portrait로 수정합니다.

                  android:label="@string/app_name"
                  android:screenOrientation="portrait"
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                  android:configChanges="orientation">


2. 배경화면 이미지 삽입

1) 시작하기

생성된 프로젝트의 불필요한 예제 코드를 삭제하고 아래와 같은 상태로 시작하겠습니다.

Classes/HelloWorldScene.cpp

#include "HelloWorldScene.h" USING_NS_CC; CCScene* HelloWorld::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object HelloWorld *layer = HelloWorld::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 HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } return true; }

Classes/HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

using namespace cocos2d;
    
class HelloWorld : public cocos2d::CCLayer
{
private:
    CCSize _screenSize; 

public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();
    
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();

    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);
};  
    
#endif // __HELLOWORLD_SCENE_H__


2) 배경 이미지 삽입

실제 게임의 이미지 구성을 잘 모르는 관계로 일단 배경과 육각형 게임판을 하나의 이미지에 모두 그렸습니다.

우선 배경 이미지인 game_back.png 파일을 Xcode를 통해 프로젝트에 추가합니다.

i) Resources 폴더에 이미지 파일 추가

Resources 폴더 위에서 우클릭을 한 후, 메뉴에서 Add files to "xxx"... 을 선택합니다.

이후 뜨는 창에서 파일을 선택하고, 창아래는 다음과 같이 선택합니다.

ii) 코드 추가

디바이스의 화면크기 정보를 통해 화면 내 image의 크기 및 위치들을 효과적으로 설정할 수 있습니다. 이 정보를 위한 변수를 class 내에 설정하겠습니다. 또한, createGameScene() 이라는 함수를 사용해서 앞으로 추가할 image 및 화면구성에 필요한 정보들을 설정합니다. 배경, 나무, 적 이미지를 모두 이 함수에서 추가하겠습니다.

Classes/HelloWorldScene.h

class HelloWorld : public cocos2d::CCLayer
{
private:
    CCSize _screenSize; 

public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  
    
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();

    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);
    
    void createGameScene(void);
};

#endif // __HELLOWORLD_SCENE_H__

cocos2d-x 에서는 CCSprite Class를 이용해 2D image를 화면에 표시합니다. createGameScene() 내에서 _screenSize 값을 초기화하고, CCSprite를 통해 배경이미지를 설정하겠습니다.

Classes/HelloWorldScene.cpp

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }

    createGameScene();

    return true;
}

void HelloWorld::createGameScene() {
    _screenSize = CCDirector::sharedDirector()->getWinSize();

    // back ground image
    CCSprite* background = CCSprite::create("game_back.png");
    background->setPosition(ccp(_screenSize.width * 0.5f, _screenSize.height * 0.5f));
    this->addChild(background);
}

프로그램 시작 시 호출될 수 있도록 init() 함수 내에 createGameScene()를 위치시킵니다.

createGameScene()에서 CCSprite로 background를 생성하고, setPosition()으로 위치 설정, this->addChild(background)를 사용하여, 현재 "Scene" 에 child로 배경이미지를 추가합니다. 위치를 설정할 때 사용하는 ccp()는 cocos2d-x 좌표계를 사용하도록 변환해주는 매크로인데, 따로 나중에 설명드리는 것이 좋겠습니다. _screenSize 기준으로 0.5f를 곱해서 화면 중앙에 위치시키는 것이 목적입니다.

코드를 추가하여 Xcode로 빌드. 정상빌드되고, 시뮬레이터에 배경이미지가 뜨면 성공!! 나무 이미지와 적 캐릭터 이미지 추가도 동일한 방법으로 하면 됩니다.


3. 나무 이미지 삽입

다음의 나무 이미지들을 추가로 작성해보겠습니다. 나무의 위치들을 조금씩 다르게 해보면서 실제 화면 상의 어디에 표시되는지 확인해보는 것도 좋을 것 같습니다.

      

1) 코드 추가

Classes/HelloWorldScene.cpp

void HelloWorld::createGameScene()
{
    _screenSize = CCDirector::sharedDirector()->getWinSize();

    // back ground image
    CCSprite* background = CCSprite::create("game_back.png");
    background->setPosition(ccp(_screenSize.width * 0.5f, _screenSize.height * 0.5f));
    this->addChild(background);

    // tree image
    CCSprite* tree = CCSprite::create("tree_01.png");
    tree->setPosition(ccp(_screenSize.width * 0.2f, _screenSize.height * 0.8f));
    this->addChild(tree);

    tree = CCSprite::create("tree_02.png");
    tree->setPosition(ccp(_screenSize.width * 0.35f, _screenSize.height * 0.8f));
    this->addChild(tree);

    tree = CCSprite::create("tree_03.png");
    tree->setPosition(ccp(_screenSize.width * 0.8f, _screenSize.height * 0.8f));
    this->addChild(tree);
}

배경 이미지와 마찬가지로 CCSprite를 이용해서 나무 이미지를 생성하고, 위치를 설정하여 현재 Scene에 추가합니다. 세 개의 나무가 각각 다른 곳에 위치하도록 값을 조정합니다.


4. 적 이미지 삽입

마지막으로 적 이미지까지 추가합니다. 다음의 대충 그린 적 이미지를 프로젝트에 추가하고, 화면 내에 생성해봅시다.

1) 코드 추가

Classes/HelloWorldScene.cpp

    tree = CCSprite::create("tree_03.png");
    tree->setPosition(ccp(_screenSize.width * 0.8f, _screenSize.height * 0.8f));
    this->addChild(tree);

    // enemy image
    CCSprite* enemy = CCSprite::create("enemy_01.png");
    enemy->setPosition(ccp(_screenSize.width * 0.7f, _screenSize.height * 0.8f));
    this->addChild(enemy);
}

5. 최종 게임 화면

배경 이미지와 나무들 그리고 적 캐릭터까지 추가하면 다음과 같은 화면을 볼 수 있습니다. 각 이미지 위치를 바꿔보고 다른 이미지도 추가해보면서 게임 화면을 구성해보는 것도 의미있을 것 같습니다.

크게 어려운 작업이 아닌데, 글만 길어지고 실제 의미있는 내용은 없는 것이 아닌가 걱정되기도 하네요. 많은 도움되셨으면 좋겠습니다. 모르는 부분 있으면 댓글로 작성해주세요.

다음에는 나무와 적 캐릭터가 움직일 수 있도록 액션을 추가해보도록 하겠습니다.

... 여기서 끝.