将SDL2 Arrow/WASD键转换为玩家运动的最佳/最坚实的方法是什么?

What is the best/most solid way to translate SDL2 arrow/WASD keys to player movement?

本文关键字:最佳 方法 是什么 玩家 WASD Arrow SDL2 转换 运动      更新时间:2023-10-16

我的问题是在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;
}

而不是在事件上采取行动以立即更改速度,而是考虑添加其他状态(数组),以记住在任何给定时刻键下的键下降。每当收到输入事件时,请更新数组并根据此重新计算速度。

例如,根据您正在制作的游戏,如果同时按下左右2,则可能要使玩家停止移动。另外,方向密钥的键盘事件将使播放器立即开始朝这个方向移动,但是您仍然需要跟踪何时没有更多按钮才能知道播放器何时应该停止移动。