From e59d00973f4b21322ba6193b4985cce3a2146979 Mon Sep 17 00:00:00 2001 From: Hans Kokx Date: Wed, 2 Sep 2026 13:36:40 +0200 Subject: [PATCH] Updated keyboard handling Signed-off-by: Hans Kokx --- raycaster.c | 104 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 81 insertions(+), 23 deletions(-) diff --git a/raycaster.c b/raycaster.c index 4fade83..464813d 100644 --- a/raycaster.c +++ b/raycaster.c @@ -40,6 +40,12 @@ int map[] = }; // clang-format on +typedef struct +{ + int w, a, d, s; // Button state on/off +} ButtonKeys; +ButtonKeys Keys; + // Function to check if a number is a power of 2 int isPowerOfTwo(int n) { @@ -459,26 +465,9 @@ void drawFloor() // * Main rendering void display() { - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - drawCeiling(); - drawFloor(); - drawMap2D(); - drawRays3D(); - drawPlayer(); - - glutSwapBuffers(); -} - -void resize(int w, int h) -{ - glutReshapeWindow(1024, 512); -} - -// * Check for key presses and move the "player" accordingly -void buttons(unsigned char key, int x, int y) -{ + // * Handle keyboard inputs // ? Move left - if (key == 'a') + if (Keys.a == 1) { // We change the angle by a small value because we're not working with // degrees. In C, we instead use radians, which is 0 -> 2π. @@ -501,7 +490,7 @@ void buttons(unsigned char key, int x, int y) } // ? Move right - if (key == 'd') + if (Keys.d == 1) { playerAngle += 0.1; @@ -515,7 +504,7 @@ void buttons(unsigned char key, int x, int y) } // ? Move forward - if (key == 'w') + if (Keys.w == 1) { // We change the X and Y values based on our delta, which is calculated // during our rotation. @@ -524,14 +513,82 @@ void buttons(unsigned char key, int x, int y) } // ? Move backwards - if (key == 's') + if (Keys.s == 1) { playerX -= playerDeltaX; playerY -= playerDeltaY; } glutPostRedisplay(); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + drawCeiling(); + drawFloor(); + drawMap2D(); + drawRays3D(); + drawPlayer(); + + glutSwapBuffers(); } +// * Key input handling +void ButtonDown(unsigned char key, int x, int y) +{ + if (key == 'a') + { + Keys.a = 1; + } + + if (key == 'd') + { + Keys.d = 1; + } + + if (key == 'w') + { + Keys.w = 1; + } + + if (key == 's') + { + Keys.s = 1; + } + + glutPostRedisplay(); +} + +void ButtonUp(unsigned char key, int x, int y) +{ + if (key == 'a') + { + Keys.a = 0; + } + + if (key == 'd') + { + Keys.d = 0; + } + + if (key == 'w') + { + Keys.w = 0; + } + + if (key == 's') + { + Keys.s = 0; + } + + glutPostRedisplay(); +} + +// * Window resizing +void resize(int w, int h) +{ + glutReshapeWindow(1024, 512); +} + +// * Check for key presses and move the "player" accordingly + void init() { @@ -574,7 +631,8 @@ int main(int argc, char *argv[]) glutReshapeFunc(resize); // Send key presses to the keyboard function - glutKeyboardFunc(buttons); + glutKeyboardFunc(ButtonDown); + glutKeyboardUpFunc(ButtonUp); glutMainLoop(); } \ No newline at end of file