터치를 사용하기 위해서는 우선 listener가 필요하다.

1
2
3
4
5
6
7
8
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
 
listener->onTouchBegan = CC_CALLBACK_2(GameLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(GameLayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(GameLayer::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(GameLayer::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
cs

터치를 하기위해서는 touch에 해당되는 llistener를 생성하고 해당 listener의 동작에 함수를 연결해주면된다.

이후 eventDispatcher에 listener를 추가시켜주면 된다.


키보드, 마우스도 마찬가지로 키보드 또는 마우스의 listener를 생성하여 추가하면된다.

1
2
3
4
5
6
7
8
9
EventListenerKeyboard* listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(Tank::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(Tank::onKeyReleased, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
 
auto mouselistener = EventListenerMouse::create();
mouselistener->onMouseMove = CC_CALLBACK_1(Tank::onMouseMove, this);
mouselistener->onMouseDown = CC_CALLBACK_1(Tank::onMouseDown, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouselistener, this);
cs

eventdispatcher는 4번줄처럼 사용할 수도 있다.




이후 해당하는 함수를 생성하여 내용을 작성해주면 해당 동작시 연결된 함수가 실행된다.

1
2
3
4
5
6
bool GameLayer::onTouchBegan(Touch * touch, Event * unused_event)
{
    jump = 650.0f;
    
    return true;
}
cs



터치 동작에서의 함수는 아래와 같다

onTouchBegan : 터치를 했을 때

onTouchMoved : 터치하고 움직였을때

onTouchEnded : 터치를 뗐을 때

onTouchCancelled : 터치를 취소했을 때 (화면밖으로 나간다거나)


마우스

onMouseDown : 마우스를 눌렀을 때

onMouseUp : 마우스를 뗐을 때

onMouseMove : 마우스를 움직였을 때

onMouseScroll : 스크롤을 움직였을 때


키보드

onKeyPressed : 키를 눌렀을 때

onKeyReleased : 키를 뗐을 때




자주 쓰는 것들로 마우스의 위치를 받아올 때에는 getLocation()을 사용하고

1
2
3
4
5
6
7
8
9
10
11
12
13
void Tank::onMouseMove(EventMouse * event)
{
    auto Barrel = getChildByName("barrel");
    Point cur = Director::getInstance()->convertToGL(event->getLocation());
 
    Point myPos = Barrel->getPosition();
    dir = cur - myPos;
    dir.normalize();
 
    barreldegree = atan2f(dir.x, dir.y);
 
    Barrel->setRotation(CC_RADIANS_TO_DEGREES(barreldegree));
}
cs


키보드의 입력을 받을 때에는 아래와 같이 KeyCode로 체크하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void Tank::onKeyPressed(EventKeyboard::KeyCode keyCode, Event * event)
{
    switch (keyCode) {
    case EventKeyboard::KeyCode::KEY_W:
        isUp = true;
        break;
 
    case EventKeyboard::KeyCode::KEY_S:
        isDown = true;
        break;
 
    case EventKeyboard::KeyCode::KEY_A:
        isLeft = true;
        break;
 
    case EventKeyboard::KeyCode::KEY_D:
        isRight = true;
        break;
    }
}
cs


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

Flappy Bird 게임 만들기 - 1  (0) 2018.03.27
충돌체크하기  (0) 2018.03.27
오브젝트 삭제하기  (0) 2018.03.26
Update 사용하기  (0) 2018.03.26
간단한 액션기능  (0) 2018.03.26
Posted by misty_
,