SDL stiff movement

i am making a pong game, lPad is left pad and rPad is the right pad, but i have a problem when any pad is moving up and when i release the up button and press down the pad stops for a while and then goes down, the other thing is i can't move both pads when pressing both controls(only one is moving) with this setup:

if(e.type == SDL_KEYDOWN) {
                    switch(e.key.keysym.sym) {

                    case SDLK_s:
                        lPad.y += 8;
                        if(lPad.y >= s.SCREEN_HEIGHT - lPad.getHeight()) {
                            lPad.y = s.SCREEN_HEIGHT - lPad.getHeight();
                        }
                        break;

                        case SDLK_w:
                        lPad.y -= 8;
                        if(lPad.y <= 0) {
                            lPad.y = 0;
                        }
                        break;

                        case SDLK_DOWN:
                        rPad.y += 8;
                        if(rPad.y >= s.SCREEN_HEIGHT - rPad.getHeight()) {
                            rPad.y = s.SCREEN_HEIGHT - rPad.getHeight();
                        }
                        break;

                        case SDLK_UP:
                        rPad.y -= 8;
                        if(rPad.y <= 0) {
                            rPad.y = 0;
                        }
                        break;

                        default:
                        break;
                    }
                }

Any idea how to fix this and make it smooth ?

Upvotes: 1

Views: 192

Answers (1)

CinchBlue
CinchBlue

Reputation: 6190

It's better to use SDL_GetKeyboardState(NULL) as the function to get input. This way, you can get the entire state of the keyboard simultaneously and thus allow for parallel inputs. If you use the while loop, each event will get caught individually, and thus be choppy.

Here is some sample code on how to use it:

  const auto * keys = SDL_GetKeyboardState(NULL);

  while(!done) {
    while(SDL_PollEvent(&e)) {
      if(e.type == SDL_QUIT) {
        done = true;
      }    
    }

    SDL_PumpEvents();

    if (keys[SDL_SCANCODE_UP]) {
      p1.set_speed(0, -60000 * delta.count());
    }
    if (keys[SDL_SCANCODE_DOWN]) {
      p1.set_speed(0, 60000 * delta.count());
    }
    if (keys[SDL_SCANCODE_LEFT]) {
      p1.set_speed(-60000 * delta.count(), 0);
    }
    if (keys[SDL_SCANCODE_RIGHT]) {
      p1.set_speed(60000 * delta.count(), 0);
    }

Also, might I suggest having a speed variable? Using pixels is not a good way to scale movement, as it depends on the resolution of the screen. Using something based on a time step is much more robust.

Upvotes: 2

Related Questions