将SDL2箭头/ WASD键转换为玩家移动的最佳/最可靠的方法是什么?

时间:2017-10-01 16:57:24

标签: c++ sdl-2 keyboard-events

我的问题是在SDL2中实现方向输入的最可靠方法是什么。

我当前代码的问题在于,您想要将播放器向左移动。按a将减小其x值,一旦释放a键,它将停止减小x值。但是,如果你想向左移动然后立即向右移动,玩家将停留一段时间然后继续向右移动。

任何建议都会非常有用。

我的键盘功能:

class KeyboardController : public Component {

public: 
TransformComponent* transform;

void init() override {
    transform = &entity->getComponent<TransformComponent>();
}

void update() override {

    if (MainGame::evnt.type == SDL_KEYDOWN) {
        switch (MainGame::evnt.key.keysym.sym)
        {
        case SDLK_w:
            transform->velocity.y = -1;

            break;
        case SDLK_a:
            transform->velocity.x = -1;

            break;
        case SDLK_s:
            transform->velocity.y = 1;

            break;
        case SDLK_d:
            transform->velocity.x = 1;

            break;
        }
    } 

    if (MainGame::evnt.type == SDL_KEYUP) {
        switch (MainGame::evnt.key.keysym.sym)
        {
        case SDLK_w:
            transform->velocity.y = 0;

            break;

        case SDLK_a:
            transform->velocity.x = 0;

            break;

        case SDLK_s:
            transform->velocity.y = 0;

            break;

        case SDLK_d:
            transform->velocity.x = 0;

            break;
        }
      }
   }
};

我的速度函数:

/* class */

Vector2D position;
Vector2D velocity;

/* other code */

void update() override {
    position.x += velocity.x * speed; //speed = 3
    position.y += velocity.y * speed;
}

1 个答案:

答案 0 :(得分:0)

不考虑事件立即改变速度,而是考虑添加额外的状态(数组),它记住在任何给定时刻哪些键都关闭了。无论何时收到输入事件,都要更新阵列并根据该值重新计算速度。

例如,根据您正在制作的游戏,如果同时按下左侧和右侧,您可能希望让玩家停止移动。或者,方向键的keydown事件会使玩家立即开始向该方向移动,但是您仍然需要跟踪何时不再按下按钮以了解玩家何时应该停止移动。