为什么这个 C 代码会导致不稳定的运动?

问题描述

我正在制作一个游戏,当按下鼠标时,角色会朝着鼠标的方向加速。沿着 +x +y 到 -x -y 轴它工作,但是沿着 +x -y 到 -x +y 轴它的行为不规律,然后由于浮点异常而崩溃,就像这个 gif:

enter image description here

显示.我正在使用 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.1);
    veLocity.y = Lerp(veLocity.y,0.1);
    
    veLocity.x = Clamp(veLocity.x,-50,50);
        veLocity.y = Clamp(veLocity.y,50);
    
    ballPosition.x += veLocity.x;
    ballPosition.y += veLocity.y;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)