키보드를 입력하기 위해서는 몇 가지 사전작업이 필요합니다.
< 헤더 >
#include "cocos2d.h"
class Keyboard : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
CREATE_FUNC(Keyboard);
// Scene 생성자/소멸자 기능
void onEnter();
void onExit();
// 키가 눌렸을 때, 뗐을 때의 함수
void KeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event);
void KeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event);
private:
// base가 될 Sprite와 키보드리스너 선언
cocos2d::Sprite* baseSprite;
cocos2d::EventListenerKeyboard* keyboard_listener;
};
< cpp >
· 기초공사
#include "Keyboard.h"
USING_NS_CC;
cocos2d::Scene * Keyboard::createScene()
{
return Keyboard::create();
}
bool Keyboard::init()
{
if (!Scene::init()) return false;
// 키보드 구현을 확인을 위한 스프라이트 초기화.
baseSprite = Sprite::create("base_sprite.png");
this->addChild(baseSprite);
return true;
}
· 리스너와 eventdispatcher를 초기화 시켜줍니다.
void Keyboard::onEnter()
{
Scene::onEnter();
// 키보드 이벤트 리스너 초기화
keyboard_listener = EventListenerKeyboard::create();
// 콜백 함수
keyboard_listener->onKeyPressed = CC_CALLBACK_2(Keyboard::KeyPressed, this);
keyboard_listener->onKeyReleased = CC_CALLBACK_2(Keyboard::KeyReleased, this);
// eventDispatcher
_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener, this);
}
void Keyboard::onExit()
{
_eventDispatcher->removeEventListener(_listener);
Scene::onExit();
}
· 키보드 리스너에 연결해줄 함수를 초기화 해줍니다.
void Keyboard::onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
Sprite->setPositionX(Sprite->getPositionX() - 5);
break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
pSprite->setPositionX(Sprite->getPositionX() + 5);
break;
case EventKeyboard::KeyCode::KEY_UP_ARROW:
Sprite->setPositionY(Sprite->getPositionY() + 5);
break;
case EventKeyboard::KeyCode::KEY_DOWN_ARROW:
Sprite->setPositionY(Sprite->getPositionY() - 5);
}
}
void Example_12::KeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
}'Cocos2d-x' 카테고리의 다른 글
| 7-2. 키보드(keyboard) - 중복키 입력 (0) | 2021.08.29 |
|---|---|
| 6. 애니메이션(Animation) (0) | 2021.08.28 |
| 5. 스케줄(schedule) (0) | 2021.08.18 |
| 4. 액션(Action) (0) | 2021.08.17 |
| 3. Menu (0) | 2021.08.07 |