1

I'm unable to move the rectangle I made in the program. There is no error message in the compiler when I run the program. Can you please tell me what I missed out in the keyboard event. Other event that I assigned to the window works fine. Instead of writing instructions down can you please show me the solution. I have been on this forever. Thanks

#include <SDL.h>
#include <stdlib.h>

int main()
{
    SDL_Window *o;
    SDL_Renderer *r;
    SDL_Event e;
    SDL_Rect q;
    int i =1;

    SDL_Init(SDL_INIT_VIDEO);

    o = SDL_CreateWindow("Game test",
                            SDL_WINDOWPOS_UNDEFINED,
                            SDL_WINDOWPOS_UNDEFINED,
                            1024,
                            800,
                            SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

    r = SDL_CreateRenderer(o, -1,SDL_RENDERER_ACCELERATED);

    while(i)
    {
        while(SDL_PollEvent(&e) !=0)
        {
            if(e.type == SDL_QUIT)
                i=0;
            else if(e.type == SDL_KEYDOWN)
            {
                switch(e.key.keysym.sym)
                {
                case SDLK_ESCAPE:
                case SDLK_q:
                    i=0;
                break;
                case SDLK_UP:
                    q.y -=10;
                break;
                case SDLK_DOWN:
                    q.y +=10;
                break;
                case SDLK_RIGHT:
                    q.x +=10;
                break;
                case SDLK_LEFT:
                    q.x -=10;
                break;
                }
            }
        }
        SDL_SetRenderDrawColor(r,0,0,255,255);
        SDL_RenderClear(r);
        // Creating the rectangle
        q.x=475;
        q.y=700;
        q.h=50;
        q.w=50;

        SDL_SetRenderDrawColor(r,0,0,0,255);

        SDL_RenderFillRect(r,&q);

        SDL_RenderPresent(r);
    }

    SDL_DestroyWindow(o);
    SDL_DestroyRenderer(r);
    SDL_Quit();

    return 0;
}
user5771881
  • 97
  • 1
  • 9

1 Answers1

2

You didn't initialize the rectangle object:

SDL_Rect q;

before potentially modifying its values in the event loop, which will result in undefined behavior:

case SDLK_UP:
    q.y -=10;
break;

Then any change made to the object is invalidated when you set constant values to it:

q.x=475;
q.y=700;
q.h=50;
q.w=50;

So the solution is clear, set the constant values to the object only when you define it.

2501
  • 25,460
  • 4
  • 47
  • 87