2016-11-22 73 views
0

我有一些行星周圍產生的宇宙飛船。我想讓他們在這個星球上飛翔。旋轉宇宙飛船,面對給定的方向矢量

我也希望他們旋轉,他們正在飛行。因爲此刻,組合屋只是其初始旋轉方向。

我不知道,如果transform.RotateAround();就是拿這個問題的正確的。 Transform.Rotate()不起作用。

所以我的問題是,怎樣才能讓我的飛船飛周圍的行星和旋轉到它們飛行的方向?

這裏是我到目前爲止的代碼:

Transform planet; // The planet to fly around 
float speed = 5;   // The movementSpeed 
Vector3 flyDirection; // The direction, it flies around 

void Start() 
{ 
    planet = GameObject.FindGameObjectWithTag("Planet").transform; // Get the transform of the planet 

    Vector3[] directions = { Vector3.left, Vector3.right, Vector3.up, Vector3.down }; // The possible directions to fly 
    flyDirection = directions[Random.Range(0, directions.Length)];   // Get a random fly direction 
} 

void Update() 
{ 
    transform.RotateAround(planet.position, flyDirection, speed * Time.deltaTime);   // Fly around the planet 
    transform.Rotate(..);  // Rotate the Object to the fly direction 
} 
+0

呃......澄清,是transform.RotateAround()'爲你工作',或者是,只要你想要麼不工作? – Serlite

+0

嘿,我真的不知道......對象正在飛來飛去,但他們並不繞着地球旋轉。他們都在東部隨機飛行... – Garzec

回答

1

移動飛船

此刻,你似乎沒有被提供正確的參數Transform.RotateAround()。具體來說,第二個參數應該是執行旋轉所圍繞的軸線,在這種情況下,該軸線應該是垂直於期望的矢量的矢量以及船/行星之間的矢量,而不是flyDirection本身。我們可以得到這樣的容易使用Vector3.Cross()

void Update() 
{ 
    // Calculating vector perpendicular to flyDirection and vector between ship/planet 
    Vector3 rotationAxis = Vector3.Cross(flyDirection, transform.position - planet.position); 
    transform.RotateAround(planet.position, rotationAxis, speed * Time.deltaTime); 

    // ... 
} 

旋轉飛船

一個快捷方式來設置對象的旋轉面對任意方向是將值賦給它transform.forward屬性。你的情況,你可以簡單地提供flyDirection作爲新forward矢量使用方法:

void Update() 
{ 
    // Calculating vector perpendicular to flyDirection and vector between ship/planet 
    Vector3 rotationAxis = Vector3.Cross(flyDirection, transform.position - planet.position); 
    transform.RotateAround(planet.position, rotationAxis, speed * Time.deltaTime); 

    // Setting spacecraft to face flyDirection 
    transform.forward = flyDirection; 
} 

如果你需要爲這個特定的四元數的值,或需要飛船的transform.up總是一個特定的方向指向(例如,普通到。地球表面),然後考慮使用Quaternion.LookRotation()來設置旋轉。

希望這會有所幫助!如果您有任何問題,請告訴我。

+0

感謝您的幫助。我傷心這個代碼沒有工作。太空船開始卡在軸上。我做了一個截圖:http://imgur.com/a/qZ54g現在他們不能再動彈了。 – Garzec

+0

@Garzec Hm,有趣。我的猜測是,如何定義可用的「方向」是一個問題 - 這四個方向與船舶停靠的軸線對齊(此時,船與行星之間的矢量基本相同作爲'flyDirection',導致交叉產品失敗)。你能提供一個關於船隻如何行爲的GIF,直到它們卡住了嗎? – Serlite