【发布时间】:2017-10-01 16:57:24
【问题描述】:
我的问题是在 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;
}
【问题讨论】:
-
问题标题“如何在 SDL 中进行键盘输入”与问题内容“如何修复我的播放器速度计算中的错误”不匹配。此外,从这段代码中也不清楚在第一次和第二次
update调用中设置的velocity是否指的是相同的速度,或者何时执行这些update调用。给定的 sn-p 与Minimal, Complete, and Verifiable example 相差甚远。 -
@VTT 如果您能想到一个明显的方法来改进问题或答案,请继续编辑它!我自己采纳了你的建议。
-
@VTT 经典堆栈溢出大声笑
标签: c++ sdl-2 keyboard-events