Updated keyboard handling

Signed-off-by: Hans Kokx <hans.d.kokx@gmail.com>
This commit is contained in:
2026-09-02 13:36:40 +02:00
parent 7d3f394dcf
commit e59d00973f
+81 -23
View File
@@ -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();
}