2012-02-19 42 views
0

我目前有一個物體在空間中飛行,我想讓物體轉向給定的座標。將對象轉向給定的座標

由於某些原因,對象旋轉而不是自我調整。

我trigganometry幾乎是不存在的,到目前爲止,我一直在使用的猜測工作,所以基本的解釋,請: -/

public void TurnTowardsDestination(double DestinationX, double DestinationY) 
{ 
    //Current Co-Ordinate of the object. 
    double positionX = x; 
    double positionY = y; 

      //My failed attempt at understanding atan2. 
    float spriteToDestAngle = (float) Math.toDegrees(Math.atan2((positionX - DestinationX),(positionY - DestinationY))); 

      //The Rotate, true is clockwise false anti-clockwise. 
    if(spriteToDestAngle > 0.0){ 
     RotateItem(true); 
    }else{ 
     RotateItem(false); 
    } 

    Log.w("direction", Integer.toString((int) spriteToDestAngle)); 
} 

可能有人點我在這個正確的教程或至少解釋如何我會讓對象向正確的方向移動。


我用一個可行的解決:(對於任何人停留在此) 來源: http://sinepost.wordpress.com/2012/02/16/theyve-got-atan-you-want-atan2/

int distX = (int) (DestinationX - x); 
    int distY = (int) (DestinationY - y); 

    double angleRadians = Math.atan2(distY, distX); 
    int angleDegrees = (int)Math.toDegrees(angleRadians); 

    //setRotation(angleDegrees); 
+3

試圖做任何形式的計算機圖形沒有基本的幾何和三角學知識將是非常不積極的。我強烈建議你學習一些! – 2012-02-19 17:08:27

+0

你能推薦一些很好的教程網站嗎? – 2012-02-19 17:11:47

+0

我建議購買例如這是一本高中數學教科書,並且通過練習來完成。 – 2012-02-19 17:53:05

回答

0

關於此by Neil Brown有綜合性文章。 Neil正在編寫基於Java的Greenfoot,所以它應該是非常直接的移植示例代碼。

+0

謝謝你的鏈接,我會去儘管它。 – 2012-02-19 18:14:43

+0

該教程幫助我弄清楚了。謝謝! – 2012-02-19 19:30:32

0

您可能會發現Line2D.relativeCCW(Point2D)在確定是非常有用的一個點是順時針還是從給定的矢量逆時針旋轉。

+0

「表示相對於此Line2D的指定座標的位置的整數」。 Line2D從哪裏來?該項目的X-Y? – 2012-02-19 17:18:22

+0

您會從對象朝向其所朝向的方向創建Line2D。 – 2012-02-19 17:19:35

0

我只想指出你的trig在這裏其實很漂亮,只是你的邏輯是不正確的。例如,如果您的目的地位於當前位置之上,則spriteToDestAngle將爲90.即使您直接指向它,代碼也會指出它應該旋轉。你應該存儲當前的方向並與之相比較。

編輯:

爲了澄清,你從來沒有考慮到當前的方向。您僅基於位置進行旋轉。

+0

我仍然建議您嘗試並利用Louis Wasserman的建議,因爲他們可能會採用更快的算法來解決順時針,逆時針問題。 – 2012-02-19 17:22:56

+0

謝謝,我正在研究它。儘管如此,我並不清楚如何實現它。 – 2012-02-19 18:15:25

相關問題