2013-04-04 58 views
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)); 

} 

代码这是线路长度方法

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错误,而且这种移动并不符合我的期望。

编辑:我已经解决了这个问题。我不确定我是否解释得很好,所以让我再试一次。如果我弄错了这些术语中的一些,我不是物理学家,所以请原谅。

我的目标是让物体以恒定速度移动,而不管方向如何。所以你可以假设你是一个朝北(0,1)方向持枪的人,然后旋转45度并开枪。枪的速度是一些标量,比如每秒50个单位。我想知道一个向量的X和Y值需要什么方向的运动。所以速度(0,50)向右旋转45度。

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

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

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

https://gamedev.stackexchange.com/questions/14602/what-are-atan-and-atan2-used-for-in-games

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

解释这个图让我意识到,如果我只是翻译线起点,终点到起点= 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); 
+0

'LineLength'需要两个'Vector2'参数,但是你用它与'Vector3'参数... – MiMo 2013-04-05 02:00:51

+0

我不确定你想要计算哪个速度 - 你有两个位置 - 速度来自哪里? – MiMo 2013-04-05 02:07:51

+0

尝试使用已知输入和已知预期输出为这些方法编写单元测试。计算似乎不正确。即使你正在计算它,你也不会使用“对面”,而且我也不确定角度的计算是否能保证它在'Math.Acos'预期的范围内。 – 2013-04-05 02:25:03

回答