Home > Software design >  SDL cannot read input from keyboard
SDL cannot read input from keyboard

Time:01-24

I am having trouble dealing with input from the keyboard. Somehow all the letter ones are extremely slow(always a big delay), most of the time it just doesn't load at all. But the up down left right and number keys all work really well. Does anyone know why?

This is my program:

while (!quit) 
{
    //Handle events on queue
    while (SDL_PollEvent(&e) != 0 )
    {
        //User requests quit
        if (e.type == SDL_QUIT)
        {
            quit = true;
        }

        //Handle input for the dot
        if (e.key.keysym.sym == SDLK_w)
            std::cout << "w ";
        if (e.key.keysym.sym == SDLK_1)
            std::cout << "1 ";
    }

CodePudding user response:

As already mentioned in your comments, you never check the event type. event.type can be SDL_TEXTINPUT or SDL_KEYDOWN for example.

Here I have a typical event loop copied from one of my projects:

while (SDL_PollEvent(&event)) {
        SDL_StartTextInput();
        switch (event.type) {
        case SDL_QUIT:
            appRunning = false;
            break;
        case SDL_TEXTINPUT:
            // here you can use event.text.text; to
            break;
        case SDL_KEYDOWN:
            char keyDown = event.key.keysym.scancode;
            break;
        }
}

Here is the official list of SDL_Events: https://wiki.libsdl.org/SDL2/SDL_Event

Hope this helped.

CodePudding user response:

SDL provides event handlers for keyboard input.

  SDL_Event e;
  .
  .
  /* Poll for events. SDL_PollEvent() returns 0 when there are no  */
  /* more events on the event queue, our while loop will exit when */
  /* that occurs.                                                  */
  while(SDL_PollEvent(&e)){
    /* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */
    switch(event.type){
      case SDL_KEYDOWN:
        //Keypress
        break;

      case SDL_KEYUP:
        //Key Release
        break;

      default:
        break;
    }

Then, you can get the value of key->keysym.sym for the keyboard input.

  • Related