将SDL2 Arrow/WASD键转换为玩家运动的最佳/最坚实的方法是什么?
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;
}
而不是在事件上采取行动以立即更改速度,而是考虑添加其他状态(数组),以记住在任何给定时刻键下的键下降。每当收到输入事件时,请更新数组并根据此重新计算速度。
例如,根据您正在制作的游戏,如果同时按下左右2,则可能要使玩家停止移动。另外,方向密钥的键盘事件将使播放器立即开始朝这个方向移动,但是您仍然需要跟踪何时没有更多按钮才能知道播放器何时应该停止移动。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?