gpt4 book ai didi

c# - 一个角度的速度

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:31 24 4
gpt4 key购买 nike

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

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

这是移动对象的代码

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 错误,并且运动没有按照我想要的方式运行。

最佳答案

以下解决方案最初由 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 错误。

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

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

这让我意识到,如果我只是将线 startingPoint, 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);

关于c# - 一个角度的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15823685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com