将 SDL2 arrow/WASD 键转换为玩家移动的 best/most 可靠方法是什么?
What is the best/most solid way to translate SDL2 arrow/WASD keys to player movement?
我的问题是在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;
}
与其根据事件立即改变速度,不如考虑添加额外的状态(数组),它会记住在任何给定时刻按下了哪些键。每当收到输入事件时,更新数组并根据该数组重新计算速度。
例如,根据您制作的游戏,您可能希望在同时按下左右键时让玩家停止移动。或者,方向键的 keydown 事件将使玩家立即开始朝该方向移动,但您仍需要跟踪何时不再按下按钮以了解玩家何时应停止移动。
我的问题是在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;
}
与其根据事件立即改变速度,不如考虑添加额外的状态(数组),它会记住在任何给定时刻按下了哪些键。每当收到输入事件时,更新数组并根据该数组重新计算速度。
例如,根据您制作的游戏,您可能希望在同时按下左右键时让玩家停止移动。或者,方向键的 keydown 事件将使玩家立即开始朝该方向移动,但您仍需要跟踪何时不再按下按钮以了解玩家何时应停止移动。