-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathController.cpp
107 lines (75 loc) · 2.19 KB
/
Controller.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
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
#include "Controller.h"
Controller::Controller()
{
deadzoneX = 0.25f;
deadzoneY = 0.25f;
}
Controller::~Controller()
{
}
int Controller::GetPort()
{
return cId + 1;
}
XINPUT_GAMEPAD * Controller::GetState()
{
return &state.Gamepad;
}
bool Controller::checkConnection()
{
int controllerId = -1;
for (DWORD i = 0; i < XUSER_MAX_COUNT && controllerId == -1; i++) {
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
if (XInputGetState(i, &state) == ERROR_SUCCESS)
controllerId = i;
}
cId = controllerId;
return controllerId != -1;
}
//if controller is unpluged or disconnected
bool Controller::Update()
{
if (cId == -1)
checkConnection();
if (cId != -1)
{
ZeroMemory(&state, sizeof(XINPUT_STATE));
if (XInputGetState(cId, &state) != ERROR_SUCCESS)
{
cId = -1;
return false;
}
//check for input and make deadzones
float normLX = fmaxf(-1, (float)state.Gamepad.sThumbLX / 32767);
float normLY = fmaxf(-1, (float)state.Gamepad.sThumbLY / 32767);
leftX = (fabs(normLX) < deadzoneX ? 0 : (fabs(normLX) - deadzoneX) * (normLX / fabs(normLX)));
leftY = (fabs(normLY) < deadzoneY ? 0 : (fabs(normLY) - deadzoneY) * (normLY / fabs(normLY)));
if (deadzoneX > 0) leftX *= 1 / (1 - deadzoneX);
if (deadzoneY > 0) leftY *= 1 / (1 - deadzoneY);
float normRX = fmaxf(-1, (float)state.Gamepad.sThumbRX / 32767);
float normRY = fmaxf(-1, (float)state.Gamepad.sThumbRY / 32767);
rightX = (fabs(normRX) < deadzoneX ? 0 : (fabs(normRX) - deadzoneX) * (normRX / fabs(normRX)));
rightY = (fabs(normRY) < deadzoneY ? 0 : (fabs(normRY) - deadzoneY) * (normRY / fabs(normRY)));
if (deadzoneX > 0) rightX *= 1 / (1 - deadzoneX);
if (deadzoneY > 0) rightY *= 1 / (1 - deadzoneY);
return true;
}
return false;
}
bool Controller::isPressed(WORD button)
{
return (state.Gamepad.wButtons & button) != 0;
}
void Controller::Vibrate(int leftVal, int rightVal)
{
// create vibration state
XINPUT_VIBRATION Vibration;
// clear vibration struct
ZeroMemory(&Vibration, sizeof(XINPUT_VIBRATION));
// Set the Vibration Values
Vibration.wLeftMotorSpeed = leftVal;
Vibration.wRightMotorSpeed = rightVal;
// Vibrate the controller
XInputSetState(cId, &Vibration);
}