From b8f66a4f05516c75c610dc8dd4274bd3232e0c3f Mon Sep 17 00:00:00 2001 From: KikooDX Date: Sun, 27 Dec 2020 01:39:05 +0100 Subject: [PATCH] Input functions macros (DRY) --- include/input.h | 4 ++++ include/input_macro.h | 12 ++++++++++++ src/input.c | 4 ++++ src/player.c | 6 +++--- 4 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 include/input_macro.h diff --git a/include/input.h b/include/input.h index 7612441..519ee84 100644 --- a/include/input.h +++ b/include/input.h @@ -4,6 +4,8 @@ #include #include +#include "input_macro.h" + #define KEYS_COUNT 6 enum { @@ -38,6 +40,8 @@ void input_init(Input *input); void input_draw_debug(Input *input); bool input_is_pressed(Input *input, uint8_t key); +/* Return duration since the last time key was pressed. */ +uint input_last_press(Input *input, uint8_t key, uint step); bool input_is_down(Input *input, uint8_t key); bool input_is_released(Input *input, uint8_t key); bool input_is_up(Input *input, uint8_t key); diff --git a/include/input_macro.h b/include/input_macro.h new file mode 100644 index 0000000..0565e5a --- /dev/null +++ b/include/input_macro.h @@ -0,0 +1,12 @@ +/* Create macros for the input system. */ + +#ifndef _DEF_INPUT_MACRO +#define _DEF_INPUT_MACRO + +#define INPUT_PRESSED(key) input_is_pressed(input, key) +#define INPUT_LAST_PRESS(key) input_last_press(input, key, step) +#define INPUT_DOWN(key) input_is_down(input, key) +#define INPUT_RELEASED(key) input_is_released(input, key) +#define INPUT_UP(key) input_is_up(input, key) + +#endif /* _DEF_INPUT_MACRO */ diff --git a/src/input.c b/src/input.c index 7b8ba84..1f7111a 100644 --- a/src/input.c +++ b/src/input.c @@ -59,6 +59,10 @@ bool input_is_pressed(Input *input, uint8_t key) { return input->states[key] == S_PRESSED; } +uint input_last_press(Input *input, uint8_t key, uint step) { + return input->last_press[key] - step; +} + bool input_is_down(Input *input, uint8_t key) { return (input->states[key] == S_DOWN) || (input->states[key] == S_PRESSED); } diff --git a/src/player.c b/src/player.c index a7a9010..6f43b6b 100644 --- a/src/player.c +++ b/src/player.c @@ -59,11 +59,11 @@ void player_step(Player *player, Input *input, const Level *level) { * i.e., if the player hold left and down move will have * move.x = -1 and move.y = 1. */ Vec move = { - (input_is_down(input, K_RIGHT) - input_is_down(input, K_LEFT)), - (input_is_down(input, K_DOWN) - input_is_down(input, K_UP)) + (INPUT_DOWN(K_RIGHT) - INPUT_DOWN(K_LEFT)), + (INPUT_DOWN(K_DOWN) - INPUT_DOWN(K_UP)) }; /* other keys */ - bool kp_jump = input_is_pressed(input, K_JUMP); + bool kp_jump = INPUT_PRESSED(K_JUMP); int xacc = move.x * ACCELERATION; /* calculate horizontal acceleration */ player->spd.x *= FRICTION; /* apply horizontal friction */ player->spd.x += xacc; /* apply horizontal acceleration */