user5771881
user5771881

Reputation: 97

Moving a square in SDL2 using C

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. Thanks (an example will also be helpful).

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

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

    SDL_Rect q;

    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);
    SDL_SetRenderDrawColor(r,0,0,255,255);
    SDL_RenderClear(r);
    //Creating a box
    q.x=475;
    q.y=700;
    q.h=50;
    q.w=50;
    SDL_SetRenderDrawColor(r,0,0,0,255);
    SDL_RenderFillRect(r,&q);
    //SDL_Delay(10);

    SDL_RenderPresent(r);

    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;
                    SDL_Delay(11);
                break;
                case SDLK_DOWN:
                    q.y +=10;
                    SDL_Delay(11);
                break;
                case SDLK_RIGHT:
                    q.x +=10;
                    SDL_Delay(11);
                break;
                case SDLK_LEFT:
                    q.x -=10;
                    SDL_Delay(11);
                break;
                default:
                break;
                }
            }
        }
    }


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

    return 0;
}

Upvotes: 0

Views: 634

Answers (2)

Mason Watmough
Mason Watmough

Reputation: 495

In SDL, you need to constantly redraw the window to see any changes you make. Since you only call the redraw function once, you only see what's happening in the very first moment of the window's creation. You simply need to add a redraw call inside of the loop, and it'll show you moving the rectangle as expected.

Upvotes: 1

Dolda2000
Dolda2000

Reputation: 25855

You are only rendering the contents of the window before you enter your event loop. Since you never redraw the contents in the event loop, it's not very strange that no changes happen.

Upvotes: 2

Related Questions