1
\$\begingroup\$

After i press and hold the key it goes forward once then pauses for a second or less then goes forward on forever. My problem is the brief pause I cant locate the issue. Thanks for your help.

    while(game){
        while (SDL_PollEvent(&e)){
            mainChar.manageEvents(e);
        }
        background.renderChar();
        mainChar.renderChar();
        SDL_RenderPresent(ren);

    }
void Character::manageEvents(SDL_Event event)
{
    switch(event.type){
        case SDL_KEYDOWN:
            KEYS[event.key.keysym.sym] = true;
            printf("true");
            handleInput();
            break;
        case SDL_KEYUP:
            KEYS[event.key.keysym.sym] = false;
            printf("false");
            break;
        default:
            break;
    }
}
void Character::handleInput()
{
    if(KEYS[SDLK_a]) { 
        dst.x--;
    }
    if(KEYS[SDLK_d]) { 
        dst.x++;
    }
    if(KEYS[SDLK_w]) { 
        dst.y++;
    }
    if(KEYS[SDLK_s]) { 
        dst.y--;
    }
}
\$\endgroup\$
2
\$\begingroup\$

Your problem is that you are not handling continuous key presses properly, what you need to do is to move the keys that need to be handled continuously outside the while loop of the SDL_PollEvent, and make sure to keep the key handling for single key press that do not require holding like "escape" inside the loop. Also make sure to handle them separately not in the same handleInput function, for example handleKeyDown (for key hold) and HandleKeyPress (for single hit).

Your code should look like this:

while(game){
    while (SDL_PollEvent(&e)){
       mainChar.keyPress(e); // for single key press
    }

    mainChar.continousKeyPress(e); // for continues key presses
    background.renderChar();
    mainChar.renderChar();
    SDL_RenderPresent(ren);
}
\$\endgroup\$
1
  • \$\begingroup\$ thank you! I am ashamed I didnt figure this out myself. much appreciated. \$\endgroup\$ – user36324 Oct 25 '13 at 3:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.