Coding & Programming/C, C++, SFML

[C/C++, SFML] 10. 키보드 이벤트(Event) 및 상태(State) 처리하기

mainCodes 2021. 4. 4. 06:47

안녕하세요 JollyTree입니다 (•̀ᴗ•́)و

 

sf::Keyboard 클래스는 눌린 키, 키눌림, 키 떼임 등의 키보드 상태에 대한 인터페이스를 제공합니다.  Event::KeyPressed, Event::KeyReleased 이벤트를 이용하여 키의 눌림과 떼임 상태를 알 수 있으며 어떤 키가 눌렸는지 event.key.code의 값을 통해 눌린 키의 값을 확인할 수 있습니다.

 

SFML 키보드 이벤트 및 상태처리

예제는 상, 하, 좌, 우 방향키가 입력되면 이벤트를 입력받아 화면의 빨간색 사각형을 입력된 키 방향에 맞춰 -10, +10 만큼씩 움직입니다.

 

스페이스(Space) 키를 누를 경우 파란색 테두리의 작은 사각형에 move() 메소드를 이용하여 소소한 애니메이션 효과를 주고 애니메이션 효과가 끝나면 빨간색 사각형의 중앙으로 작은 사각형을 이동시킵니다.

 

SFML Keyboard 이벤트 및 상태 처리 예제 코드(Example): 

 

 

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
#include <SFML/Graphics.hpp>
#include <iostream>
 
using namespace std;
using namespace sf;
 
#define CIRCLE_RADIUS   100.f
 
int main()
{
    float x = 0, y = 0;
 
 
    //키보드 입력 따라 움직일 RectangleShape 객체
    RectangleShape rect_shape(Vector2f(200200));
    RectangleShape small_rect_shape(Vector2f(1010));
 
    rect_shape.setFillColor(Color::Green);
    rect_shape.setOutlineColor(sf::Color::Red);
    rect_shape.setOutlineThickness(20);
    rect_shape.setPosition(x, y);
 
    small_rect_shape.setFillColor(Color::Yellow);
    small_rect_shape.setOutlineColor(sf::Color::Blue);
    small_rect_shape.setOutlineThickness(20);
    small_rect_shape.setPosition(x, y);
 
    cout << "프로그램이 시작되었습니다." << endl;
 
    //화면 크기, 캡션 이름 설정
    RenderWindow app(VideoMode(504504), "https://maincodes.tistory.com/");
    app.setFramerateLimit(60);  //프레임 비율 설정
 
    //SFML 메인 루프 - 윈도우가 닫힐때 까지 반복
    while (app.isOpen())
    {
        Event event;
 
        //이벤트 처리
        while (app.pollEvent(event))
        {
            //프로그램 종료 이벤트 처리
            if (event.type == Event::EventType::Closed)
            {
                app.close();
                cout << "프로그램이 종료되었습니다." << endl;
            }
 
            //키보드 눌림(Pressed) 이벤트
            if (event.type == Event::KeyPressed)
            {
                switch (event.key.code)
                {
                case Keyboard::Left:
                {
                    cout << "Left 키 눌림 " << endl;
                    x -= 10;
                    break;
                }
 
                case Keyboard::Right:
                {
                    cout << "Right 키 눌림 " << endl;
                    x += 10;
                    break;
                }
 
                case Keyboard::Up:
                {
                    cout << "UP 키 눌림 " << endl;
                    y -= 10;
                    break;
                }
 
                case Keyboard::Down:
                {
                    cout << "Down 키 눌림 " << endl;
                    y += 10;
                    break;
                }
 
                case Keyboard::Space:
                {
                    cout << "Space 키 눌림 " << endl;
 
                    float speed = 3;
 
                    //작은 사각형 애니메이션 효과
                    for (int i = 0; i < 50; i += speed)
                    {
                        small_rect_shape.move(speed * 1, speed * 1);
                        app.draw(small_rect_shape);
                        app.display();
                    }
 
                    //작은 사각형 원 위치
                    small_rect_shape.setPosition(Vector2f((float)x, (float)y));
                    break;
                }
                default:
                    cout << "키 눌림((key.code) = " << event.key.code << endl;
                    break;
                }
            }
            if (event.type == Event::KeyReleased)
                cout << "키 떼임((key.code) = " << event.key.code << endl;
        }
 
        //배경화면을 흰색으로 clear
        app.clear(Color::White);
 
        //rect_shape 위치 보정
        rect_shape.setPosition(Vector2f(x - 100.f, y - 100.f));
        app.draw(rect_shape);
 
        app.draw(small_rect_shape);
 
        //프레임을 스크린에 출력
        app.display();
    }
 
    return 0;
}
cs

 

예제는 마우스와 유사하게 메인 윈도우가 포커스 밖에 있을 경우 아무런 이벤트를 받지 않습니다. 따라서 키 눌림, 떼임 등의 키보드  상태에 대한 아무런 정보를 출력하지 않습니다.

실행결과(Output):

 

SFML 키보드 예제 실행 결과

키보드 눌림의 경우 isKeyPressed() 메소드를 이용하여 다음과 같은 형태로도 표현할 수 있는데 이 방법은 동시키 눌림을 구현할 수 있다는 장점이 있습니다. 이 방법은 다음 포스팅 때 정리해서 올리겠습니다.

 

    if (Keyboard::isKeyPressed(Keyboard::Left))

        y -= 10;

 

    if (Keyboard::isKeyPressed(Keyboard::Right))

        y += 10;

 

이번 포스팅에서는 SFML의 키보드 이벤트 처리 방법에 대해 알아보았습니다. 이상 JollyTree였습니다 (•̀ᴗ•́)و