SDL运动停止

时间:2014-10-07 11:38:37

标签: c++ sdl sdl-2

我在SDL和C ++中构建了一个太空射击游戏,到目前为止,该运动正在发挥作用。 问题是,如果我按下,让我们说UP和我添加RIGHT键(现在我同时按下向上和向右),船只会停留很短时间。

当它向上移动+向右移动时也是如此,如果我放开第二个按下的键,移动停止,我必须再次按下键开始。

我猜这是持有和添加按键的一些问题。如果有人能告诉我在哪里看,那就太好了。

我正在使用SDL2。

Uint8 const *keystate = SDL_GetKeyboardState(NULL);

keystate = SDL_GetKeyboardState(NULL);
while(exit == false) {
    if( SDL_PollEvent(&event) != 0 ) {
        if(event.type == SDL_QUIT) {
            exit = true;
        }
        if (keystate[SDL_SCANCODE_LEFT] ) {
            ship.move(-2, 0);
        }
        if (keystate[SDL_SCANCODE_RIGHT] ) {
            ship.move(2, 0);
        }
        if (keystate[SDL_SCANCODE_UP] ) {
            ship.move(0, -2);
        }
        if (keystate[SDL_SCANCODE_DOWN] ) {
            ship.move(0, 2);
        }
        if (keystate[SDL_SCANCODE_SPACE]) {
            ship.shoot();
        }
    }
    SDL_BlitSurface(ship.getSurface(), NULL, surface, ship.getRect());
    SDL_UpdateWindowSurface( window );
    SDL_FillRect(surface, NULL, 0);
}

没有像这样的东西修复:

if (keystate[SDL_SCANCODE_DOWN] && keystate[SDL_SCANCODE_RIGHT) {
        ship.move(2, 2);
    }

1 个答案:

答案 0 :(得分:4)

当关键状态发生变化时会触发

SDL_PollEvent,我相信如果按住该键,您将根据按键重复率获得事件。您应该将键盘检查代码移到if( SDL_PollEvent(&event) != 0 )

之外
while(exit == false) {
    if( SDL_PollEvent(&event) != 0 ) {
        if(event.type == SDL_QUIT) {
            exit = true;
        }
    }

    // you may need to take into account elapsed time to achieve constant speed
    // regardless of frame rate
    if (keystate[SDL_SCANCODE_LEFT] ) {
        ship.move(-2, 0);
    }
    if (keystate[SDL_SCANCODE_RIGHT] ) {
        ship.move(2, 0);
    }
    if (keystate[SDL_SCANCODE_UP] ) {
        ship.move(0, -2);
    }
    if (keystate[SDL_SCANCODE_DOWN] ) {
        ship.move(0, 2);
    }
    if (keystate[SDL_SCANCODE_SPACE]) {
        ship.shoot();
    }

    SDL_BlitSurface(ship.getSurface(), NULL, surface, ship.getRect());
    SDL_UpdateWindowSurface( window );
    SDL_FillRect(surface, NULL, 0);
}

同时阅读the doc,您的代码在那里被明确命名为错误,并提供了正确代码的示例。

相关问题