summaryrefslogtreecommitdiffhomepage
path: root/KeyboardController.cpp
blob: 15ed1ff609c4aa67afe2fadda603a3c44c9ff858 (plain)
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
#include "KeyboardController.h"

#include <math.h>

#include <raylib.h>


static const float DIAGONAL {static_cast<float>(sin(static_cast<float>(M_PI) / 4.0f))};


static int check_axis(int negative_key, int positive_key, int last);



KeyboardController::KeyboardController() :
    x_axis {0},
    y_axis {0}
{
}


Vector2
KeyboardController::direction()
{
    x_axis = check_axis(KEY_LEFT, KEY_RIGHT, x_axis);
    y_axis = check_axis(KEY_UP, KEY_DOWN, y_axis);
    if (x_axis != 0 && y_axis != 0)
        return {x_axis * DIAGONAL, y_axis * DIAGONAL};
    return {static_cast<float>(x_axis), static_cast<float>(y_axis)};
}


int
check_axis(const int negative_key, const int positive_key, const int last)
{
    int next = last;
    if (last == 1 && IsKeyReleased(positive_key)) {
        if (IsKeyDown(negative_key))
            next = -1;
        else
            next = 0;
    }
    else if (last == -1 && IsKeyReleased(negative_key)) {
        if (IsKeyDown(positive_key))
            next = 1;
        else
            next = 0;
    }
    if (IsKeyPressed(positive_key))
        next = 1;
    else if (IsKeyPressed(negative_key))
        next = -1;
    return next;
}