2016-06-10 106 views
2

我一直在尝试用正确的模拟棒创建延迟旋转效果。 下面的代码根据正确的模拟摇杆的输入获取角度并使物体稳定靠近。 由于atan2是-pi到pi的范围,所以变化的旋转总是倾向于移动通过0弧度而不是pi。有没有办法让角度向相反的方向行进?使用atan2延迟旋转

private void Angle() 
    { 
     //Angle to go to 
     RotationReference = -(float)(Math.Atan2(YR, XR)); 

     //Adds on top of rotation to steadily bring it closer 
     //to the direction the analog stick is facing 
     Rotation += (RotationReference - Rotation) * Seconds *15; 
     Console.WriteLine(RotationReference); 
    } 

编辑:

我使用其间的建议引起2PI之间的过渡为0的一个问题的方法尝试。这导致我尝试了别的东西。我不知道为什么它不起作用。

private void Angle() 
    { 
     //Angle to go to 
     RotationReference = -(float)(CorrectedAtan2(YR, XR)); 

     //Adds on top of rotation to steadily bring it closer 
     //to the direction the analog stick is facing 
     if (Math.Abs(RotationReference - Rotation) > Math.PI) 
      Rotation += ((float)(RotationReference + Math.PI * 2) - Rotation) * Seconds * 15; 
     else Rotation += (RotationReference - Rotation) * Seconds *15; 
     Console.WriteLine(RotationReference); 
    } 

    public static double CorrectedAtan2(double y, double x) 
    { 
     var angle = Math.Atan2(y, x); 
     return angle < 0 ? angle + 2 * Math.PI: angle; 
    } 

背后的想法是,如果你需要旅行超过180度,你会使角度超过360度。这应该消除逆转方向的需要。

+0

我认为你在这里寻找的关键词是补间。 – craftworkgames

回答

0

一些实验,我设法使它工作之后。 感谢InBetween for CorrectedAtan2方法。 for循环用于检查所有需要添加pi的实例,以避免发生不和谐的转换。

private float Angle(float y, float x) 
    { 
     //Angle to go to 
     RotationReference = -(float)(CorrectedAtan2(y, x)); 

     for (int i = 0; i < 60; i++) 
     { 
      if (Math.Abs(RotationReference - Rotation) > Math.PI) 
       RotationReference = -(float)(CorrectedAtan2(y, x) + 
        (Math.PI * 2 * i)); 
     } 
     //Adds on top of rotation to steadily bring it closer 
     //to the direction the analog stick is facing 
     return Rotation += (RotationReference - Rotation) * Seconds * 15; 
    } 

    public static double CorrectedAtan2(double y, double x) 
    { 
     var angle = Math.Atan2(y, x); 
     return angle < 0 ? angle + 2 * Math.PI: angle; 
    } 
0

只需要修正的角度以适应[0, 2·pi]范围:

public static double CorrectedAtan2(double y, double x) 
{ 
    var angle = Math.Atan2(y, x); 
    return angle < 0 ? angle + 2 * Math.PI : angle; 
} 
+0

我尝试了一些类似的东西(尽管你的代码比我的代码好)。但是,当从2PI再次回到零时,这会颠倒问题。我能想到的唯一解决方案将涉及使用小于零且大于2PI的弧度,从而消除从2PI到零的尴尬转换。可悲的是,我有限的编程经验使我无法知道如何做到这一点。感谢您的帮助。 –