简体   繁体   中英

Weird SDL Keyboard Issues

So I've tried this on two machines running two different OS's and the same thing happens between them.

#include <iostream>
#include <SDL2/SDL.h>

int main(int argc, char *argv[])
{

bool running = true;

SDL_Init( SDL_INIT_EVERYTHING);

SDL_Window* win = SDL_CreateWindow("test", 100, 100, 800, 600, 
SDL_WINDOW_SHOWN);
SDL_Renderer* ren = SDL_CreateRenderer(win, -1, 0);

int r = 0;

while(running)
{
    SDL_Event event;
    SDL_PollEvent(&event);

    switch(event.type)
    {
        case SDL_QUIT:
            running = false;
            break;

        case SDL_KEYDOWN:
            switch(event.key.keysym.sym)
            {
                case SDLK_d:
                    r++;
                    break;
                case SDLK_RIGHT:
                    r++;
                    break;
            }
            break;
    }

    SDL_SetRenderDrawColor(ren, r, 255, 255, 255);
    SDL_RenderClear(ren);

    SDL_RenderPresent(ren);
}

SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();

return 0;
}

When holding down the right arrow key, it flickers, r is increasing much faster.

When holding down d, it slowly increases.

Why?

SDL_PollEvent returns 1 if there is a pending event or 0 if there are none available. You don't check return status and look into event anyway, even if you have no reason to. What you'll find here is pretty much undefined (most likely just old data - reading the same event over and over again, even if it didn't happen that often).

Correct event handling is done within a loop:

while(running) {
    SDL_Event ev;
    while(SDL_PollEvent(&ev)) {
        // process event here
    }
    // draw here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM