2012-03-10 87 views
6

我開始使用Unity進行開發。 我在做這樣的事情:Unity3D C#計算旋轉後的正確轉發

if(Input.GetKey(KeyCode.A))newValues[1]-=this.turnSpeed*(float)Time.deltaTime; 
    if(Input.GetKey(KeyCode.D))newValues[1]+=this.turnSpeed*(float)Time.deltaTime; 
    transform.Rotate(0, newValues[1], 0); 


    if(Input.GetKey(KeyCode.W))newValues[0]+=this.speed*transform.forward.z*(float)Time.deltaTime; 
    if(Input.GetKey(KeyCode.S))newValues[0]-=this.speed*transform.forward.z*(float)Time.deltaTime; 


    transform.position = new Vector3(transform.position.x, transform.position.y, (float)newValues[0]); 

所以我旋轉,我可以移動,但移動只是在Z行,我知道我呼籲在Z特定的運動。 但使用JavaScript,我可以做一些事情

 transform.forward+=this.speed*transform.forward*(float)Time.deltaTime; 

所以我並不需要做新的向量處理,並複製到一個獨立的變量,它的工作原理就像一個魅力,利用旋轉和利用爲導向,以自己的時候它被旋轉了。

+0

你或許應該修改標題和標籤。所使用的統一標籤是指MS應用程序塊中的依賴注入容器。你可能指的是unity-3D,如果這是爲了遊戲,你可能需要添加一個合適的標籤。 – Tod 2012-03-10 01:09:50

+0

如果在C#代碼中放置'transform.forward + = this.speed * transform.forward *(float)Time.deltaTime',會發生什麼? Javascript和C#都編譯爲相同的.NET中間語言,因此如果代碼稍有不同,幾乎任何可能的東西都可能在另一箇中。 – 2012-03-10 01:32:29

+0

它不工作,它是一個只讀變量 – Lefsler 2012-03-10 02:37:44

回答

7

您可能會誤解transform.forward的用法。 transform.forward只是一個向量來告訴你你的gameObject面對什麼方向,它取決於transform.rotation。

如果你想將你的遊戲對象,總是使用transform.position

transform.position += this.speed * transform.forward * (float)Time.deltaTime; 
+1

謝謝,但我如何實現旋轉? – Lefsler 2012-03-14 22:22:49

+2

非常舊的線程,但想要恢復它,因爲你已經提到「如果你想移動你的遊戲對象,總是使用transform.position」實際上,如果遊戲對象是剛體,那麼它應該通過添加力來移動,因爲直接修改變換可能導致不切實際的行爲。但對於運動機構你的陳述是真的 – Eklavyaa 2014-10-08 12:28:55

+0

你是對的,@Eklavyaa – Chchwy 2014-10-15 07:03:29