KEY_D isn't working for me

Everything else works fine. However when the window pops up, the circle isn’t moving when I press the D key, or any other key for that matter.
I decreased the circleX increment from +10 to +1, but other than that everything should be identical to the lecture’s example. I don’t know why KEY_D isn’t working.

You did a good job with KEY_D and the code inside of the if-statement. But how you’ve implemented circleX and circleY along with DrawCircle effects the end-result.

If I compare your code with the code in the lecture’s gitlab page, I can see a few things. (You can see the lecture’s code below for convenience)

  1. Your initializations of circleX and circleY are inside the while-loop, what this means is that at the start of every frame, these variables will be set back to the value you initialized them (175 and 150, respectively).
  2. You change the value of circleX on KEY_D after you call DrawCircle. Normally, this wouldn’t be an issue, you would just see the effects on the next frame. But when taken into account with point #1, this means that you would never see the changes to circleX. Even if DrawCircle was after the if-statement for KEY_D, you would just see the circle wiggle very rapidly.

You can fix points 1 and 2 with one change, all you need to do is move line 17 and 18 (int circleX{175}; and int circleY{150};) out of the while-loop. Just below the call to InitWindow looks good.

#include "raylib.h"
int main()
{
    int width;
    width = 350;
    InitWindow(width, 200, "Stephen's Window");
    // window dimensions
    int width{350};
    int height{200};
    InitWindow(width, height, "Stephen's Window");

    // circle coordinates
    int circle_x{175};
    int circle_y{100};

    SetTargetFPS(60);
    while (WindowShouldClose() == false)
    {
        BeginDrawing();
        ClearBackground(WHITE);

        DrawCircle(175, 100, 25, BLUE);
        // Game logic begins

        DrawCircle(circle_x, circle_y, 25, BLUE);

        if (IsKeyDown(KEY_D))
        {
            circle_x = circle_x + 10;
        }
        if (IsKeyDown(KEY_A))
        {
            circle_x = circle_x - 10;
        }

        // Game logic ends
        EndDrawing();
    }
}

That worked.
Thanks for the help!

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms