0

我正在制作一个游戏,当按下鼠标时,角色会朝鼠标的方向加速。沿着 +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;
4

0 回答 0