2

我试图找到一个角度的速度。

为此,我尝试使用三角形,但遇到了障碍。

这是移动对象的代码

Velocity = new Vector3((float)Math.Cos(MathC.AngleToPoint(EnemyObject.transform.position, PlayerPosition)),
              (float)Math.Sin(MathC.AngleToPoint(EnemyObject.transform.position, PlayerPosition)), 0);

这是 AngleToPoint 方法

public static double AngleToPoint(Vector3 startingPoint, Vector3 endPoint)
{
    double hypotenuse = LineLength(startingPoint, endPoint);
    double adjacent = LineLength(startingPoint, new Vector3(endPoint.x, startingPoint.y, 0));
    double opposite = LineLength(endPoint,  new Vector3(endPoint.x, startingPoint.y, 0));

    double angle = adjacent / hypotenuse;


    return Math.Acos(DegreeToRadian(angle));

}

这是 LineLength 方法

public static float LineLength(Vector2 point1, Vector2 point2)
{
    return Math.Abs((float)Math.Sqrt(Math.Pow((point2.x - point1.x), 2)+Math.Pow((point2.y - point1.y),2)));

}

我收到了很多 NaN 错误,而且运动的行为不像我想要的那样。

4

1 回答 1

1

以下解决方案最初由问题作者D Yamamoto发布。


我已经解决了这个问题。我不确定我是否能很好地解释自己,所以请允许我再次尝试这样做。我不是物理学家,如果我弄错了其中一些术语,请原谅。

我的目标是让物体以恒定的速度移动,而不管方向如何。所以你可以假设你是一个人,拿着枪朝北 (0, 1) 方向旋转 45 度并开火。枪的速度是一些标量,例如每秒 50 个单位。我想知道一个向量的 X 和 Y 值我需要在任何方向上进行移动。所以 Velocity (0, 50) 向右旋转了 45 度。

我知道 Velocity.X = SpeedCos(Angle) 和 Velocity.Y = SpeedSin(Angle),但我需要找到 Angle 的值。

为此,我的思路是根据起始位置和目的地制作一个直角三角形,然后使用三角函数找到角度。

public static double AngleToPoint(Vector3 startingPoint, Vector3 endPoint)
{
    double hypotenuse = LineLength(startingPoint, endPoint);
    double adjacent = LineLength(startingPoint, new Vector3(endPoint.x, startingPoint.y, 0));
    double opposite = LineLength(endPoint,  new Vector3(endPoint.x, startingPoint.y, 0));

    double angle = adjacent / hypotenuse;


    return Math.Acos(DegreeToRadian(angle));

}

这段代码正在制作一个直角三角形。相反的原因是即使没有使用它也是因为我尝试了多种方法来尝试完成此操作,但一直遇到错误。在制作一个直角三角形后,它需要 adj 和 hypo 来获得 cos(adj/hypo),然后我调用 Acos 给我以弧度为单位的角度。但是,这不起作用,它没有正确返回我的角度并产生了很多 NaN 错误。

搜索后,我找到了解释 atan2的 gamedev.se Q&A,其中包括这张图片:

http://i.stack.imgur.com/xQiWG.png

这让我意识到,如果我只是将行 startPoint, endPoint 转换为 startingPoint = 0,我可以调用 atan2 并返回我想要的角度。这是实现这一点的代码。

public static double GetAngleToPoint(Vector3 startingPoint, Vector3 endPoint)
{
    endPoint -= startingPoint;
    return Math.Atan2(endPoint.y, endPoint.x);
}

Velocity = new Vector3(Speed * (float)Math.Cos(MathC.GetAngleToPoint(StartingPosition, PlayerPosition)),
              Speed * (float)Math.Sin(MathC.GetAngleToPoint(StartingPosition, PlayerPosition)), 0);
于 2019-07-20T03:04:11.453 回答