2016-06-10 109 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到零的尷尬轉換。可悲的是,我有限的編程經驗使我無法知道如何做到這一點。感謝您的幫助。 –