-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.cpp
63 lines (51 loc) · 1.81 KB
/
input.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
#include "input.h"
int Input::keyStates[keys]{}; // https://wiki.libsdl.org/SDL2/SDLKeycodeLookup
int Input::mouseStates[mouseButtons]{}; // https://wiki.libsdl.org/SDL2/SDL_MouseButtonEvent
int Input::mouseWheel = 0;
Tmpl8::vec2 Input::mousePosition = Tmpl8::vec2(0, 0);
bool Input::GetKeyDown(SDL_Scancode key) {
if (key < 0 || key > keys) return false;
return keyStates[key] == 1;
}
bool Input::GetKeyUp(SDL_Scancode key) {
if (key < 0 || key > keys) return false;
return keyStates[key] == 3;
}
bool Input::GetKey(SDL_Scancode key) {
if (key < 0 || key > keys) return false;
return keyStates[key] == 2 || keyStates[key] == 1;
}
bool Input::GetMouseButtonDown(int button) {
return mouseStates[button] == 1;
}
bool Input::GetMouseButtonUp(int button) {
return mouseStates[button] == 3;
}
bool Input::GetMouseButton(int button) {
return mouseStates[button] == 2 || mouseStates[button] == 1;
}
// 0 = inactive, 1 = pressed, 2 = held, 3 = released
void Input::SetKeyState(SDL_Scancode key, bool state) {
if (key < 0 || key > keys) return;
if (keyStates[key] == 2 && state) return; // Key already held
keyStates[key] = state ? 1 : 3;
}
void Input::SetMouseState(int button, bool state) {
if (button < 0 || button > mouseButtons) return;
if (mouseStates[button] == 2 && state) return; // Button already held
mouseStates[button] = state ? 1 : 3;
}
/// <summary>
/// Update states of keys and buttons for held and released states.
/// </summary>
void Input::Update() {
for (int i = 0; i < keys; i++) {
if (keyStates[i] == 1) keyStates[i] = 2; // Pressed -> Held
else if (keyStates[i] == 3) keyStates[i] = 0; // Released -> Up
}
for (int i = 0; i < mouseButtons; i++) {
if (mouseStates[i] == 1) mouseStates[i] = 2; // Pressed -> Held
else if (mouseStates[i] == 3) mouseStates[i] = 0; // Released -> Up
}
mouseWheel = 0;
}