代码之家  ›  专栏  ›  技术社区  ›  Cobblestonie

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

  •  1
  • Cobblestonie  · 技术社区  · 8 年前

    我的问题是,在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 回复  |  直到 8 年前
        1
  •  0
  •   Vladimir Panteleev    8 年前

    与其对事件采取行动立即改变速度,不如考虑添加额外的状态(一个数组),以记住在任何给定时刻哪些键处于下降状态。任何时候接收到输入事件时,都要更新阵列,并在此基础上重新计算速度。