Circle don't move by clicking "A" or "D" key

Hi,
I made a game that i can close it by pressing X key or ESCAPE key, until this tutorial everything was good, but when i debug it and run it, I cant move the circle to left and right by pressing “A” or “D”, nothing happen by pressing these keys. please show me the way.

This is the .cpp code:

#include "raylib.h"

int main()
{
    // Window layout
    int width{350};
    int hight{200};
    InitWindow(width, hight, "Halim Shams");

    SetTargetFPS(60);
    while (WindowShouldClose() == false)
    {
        // Circle demations
        int circle_x{175};
        int circle_y{100};

        BeginDrawing();
        ClearBackground(WHITE);
        DrawCircle(circle_x, circle_y, 25, BLUE);

        // Game starts

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

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

        //Game ends
        EndDrawing();
    }
    
}

Try to keep in mind that when you do something like this: int circle_x{175};

You are doing two actions:
int circle_x; // action 1
circle_x = 175; // action 2

Every time your loop starts, the value of circle_x is being reassigned the initial value again, overwriting your increment. The circle is then continuously being drawn in the same place.

If you move your variables to just before the loop, they’ll be initialized only once and further changes inside the loop will be retained. Check the difference when running this:

#include <iostream>
#include <string>

int main()
{
    int a{10};
    for(int i = 0; i < 10; i++) {
        int b{10};
        
        std::cout << i << ": a = " << a << std::endl;
        std::cout << i << ": b = " << b << std::endl << std::endl;
        
        a += 10;
        b += 10;
    }
}

1 Like

So why the Stephen’s (instructor of this course) code run with this code?
and what to change now in my “cpp” code to move my circle Left and Right?

I checked the video for 11_ag_cpp (not sure how this question ended up under 3_ag_cpp tag), and Stephen declares and initializes the variables before the while() loop as I have done with the variable “a” in my example.

So you need to do the same, move your int circle_x… and int circle_y… lines to before the while() loop.

Please look at the example I provided more closely and see the difference in how a and b were placed, and how this affects the results when it runs and prints out on the right hand side. It should be clear, the only difference is that I used a for() loop instead of a while() to serve the example a fixed number of times.

This is from the video, notice the placement and compare with your own:

1 Like

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

Privacy & Terms