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