c - 为什么这个 C 代码会导致不稳定的运动?
问题描述
我正在制作一个游戏,当按下鼠标时,角色会朝鼠标的方向加速。沿着 +x +y 到 -x -y 轴它可以工作,但是沿着 +x -y 到 -x +y 轴它的行为不规律,然后崩溃并出现浮点异常,就像这个 gif所示:我正在使用 raylib,这是我的代码:
Vector2 goToPosition = GetMousePosition();
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) {
Vector2 relative = {goToPosition.x - ballPosition.x, goToPosition.y - ballPosition.y};
if (abs(relative.x) > abs(relative.y)) {
velocity.x += relative.x > 0 ? 5 : -5;
velocity.y += relative.y > 0 ? 5 * (abs(relative.x) / abs(relative.y)) : 5 * -(abs(relative.x) / abs(relative.y));
}
else if (abs(relative.x) < abs(relative.y)) {
velocity.x += relative.x > 0 ? 5 * (abs(relative.y) / abs(relative.x)) : 5 * -(abs(relative.y) / abs(relative.x));
velocity.y += relative.y > 0 ? 5 : -5;
}
else if (abs(relative.x) > 0) {
velocity.x += relative.x > 0 ? 5 : -5;
velocity.y += relative.y > 0 ? 5 : -5;
}
printf("%f, %f \n", velocity.x, velocity.y);
}
velocity.x = Lerp(velocity.x, 0, 0.1);
velocity.y = Lerp(velocity.y, 0, 0.1);
velocity.x = Clamp(velocity.x, -50, 50);
velocity.y = Clamp(velocity.y, -50, 50);
ballPosition.x += velocity.x;
ballPosition.y += velocity.y;
解决方案
推荐阅读
- c++ - 为什么我不能编译 Boost.Serialization 演示?
- r - R通过部分匹配合并2个表/数据框
- kotlin - 如何在kotlin中声明一个可为空的函数参数
- python - groupby 获取平均值,使用动态条件
- asp.net - Crystal Report 2016 支持 Asp 经典?
- eclipse - 如何在rcp中添加python透视图
- javascript - 如何让我的 firebase 侦听器在 React Native 应用程序中将数据加载到我的 redux 状态,以便我可以在 ComponentDidMount 函数中读取数据?
- python - 如何浏览 txt 文件并发送带有特定数据的请求
- excel - EXCEL - 做数据范围变化的图表
- .net - .Net Core MVC + ReactJS,Safari 浏览器中的 Webpack 问题