【问题标题】:Calculating direction angle from x and y speed从 x 和 y 速度计算方向角
【发布时间】:2021-06-26 22:12:18
【问题描述】:

我正在使用 Game Maker 类型的程序(但不是真正的 Game Maker)开发游戏,因为我在用真实语言编写游戏(可以编写普通应用程序,但不能编写游戏)方面失败了很多次。

无论如何,在我使用方向功能的程序中,有时被证明是错误的。但是物体的 x 和 y 速度总是正确的,所以我想从这些计算方向角(以度为单位)。不幸的是,我不是数学天才,而且我在三角​​学上总是失败;(。你能帮帮我吗?

我的游戏制作IDE的角坐标系如下:

         270 deg.
  180 deg.      0 deg.
         90 deg.

定位系统就像在大多数环境中一样(左上角的 0,0)

【问题讨论】:

    标签: trigonometry angle


    【解决方案1】:

    数学库通常带有一个名为 atan2 的函数,仅用于此目的:

    double angle = atan2(y, x);
    

    角度以弧度为单位;乘以 180/PI 以转换为度数。角度的范围是从 -pi 到 pi。 0 角是正 x 轴,角度顺时针增长。如果您想要一些其他配置,则需要进行微小的更改,例如 0 角为负 y 轴,范围为 0 到 359.99 度。

    使用atan2 而不是atan 或任何其他反三角函数的主要原因是因为它为您确定了正确的角象限,您不需要自己用一系列if-statements.

    【讨论】:

      【解决方案2】:

      使用反正切函数。应该是这样的:

      double direction(double x, double y) {
          if (x > 0)
              return atan(y/x);
          if (x < 0)
              return atan(y/x)+M_PI;
          if (y > 0)
              return M_PI/2;
          if (y < 0)
              return -M_PI/2;
          return 0; // no direction
      }
      

      (其中x和y是水平和垂直速度,M_PI是pi,atan是反正切函数。)

      【讨论】:

        【解决方案3】:

        特别是在游戏制作器中,您可以使用以下内容:

        direction = point_direction(x, y, x+x_speed, y+y_speed)
        speed = point_distance(x, y, x+x_speed, y+y_speed)
        

        (比较当前和未来的 x/y 坐标和返回值)

        逆过程得到x/y_speed:

        x_speed = lengthdir_x(speed, direction)
        y_speed = lengthdir_y(speed, direction)
        
        Note: Added this post because its still viewed in relation to Game Maker:
        Studio and its specific functions. Maybe it has no value for the person who
        asked originally but i hope it will help some Game Maker users who wander here.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-25
          • 2017-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-28
          相关资源
          最近更新 更多