2017-03-17 31 views
0

我想讓定向燈以恆定速度旋轉。這是我有的代碼:如何更改方向燈的旋轉? (C#,Unity 5.5)

using System.Collections; 
using UnityEngine; 

public class LightRotator : MonoBehaviour { 

    void Update() { 
     transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + 1.0f, transform.rotation.z); 
    } 
} 

但是,這只是把光放在一個奇怪的地方,並把它留在那裏。我究竟做錯了什麼?

這是光的旋轉之前我運行遊戲(應該是起始位置): Start Position

一旦遊戲開始時,它改變(在保持)這樣的: Wrong Position

回答

0

也許嘗試transform.localEulerAngles

transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, 
      transform.localEulerAngles.y + 1.0f, transform.localEulerAngles.z); 

但我建議你添加Time.deltaTime到,或者你的光將在共同的幀速率旋轉mputer運行它。所以如果你想要一個恆定的速度,修改它的值。

我編輯了以下內容來製作完整的示例。 OP在一個軸上說在一定程度上停止。我已經擴展了這個以下面的代碼來展示它,它可以在任何軸和任何方向上工作,可以在運行時修改。

using UnityEngine; 

public class rotate : MonoBehaviour { 

    public float speed = 100.0f; 
    Vector3 angle; 
    float rotation = 0f; 
    public enum Axis 
    { 
     X, 
     Y, 
     Z 
    } 
    public Axis axis = Axis.X; 
    public bool direction = true; 

    void Start() 
    { 
     angle = transform.localEulerAngles; 
    } 

    void Update() 
    { 
     switch(axis) 
     { 
      case Axis.X: 
       transform.localEulerAngles = new Vector3(Rotation(), angle.y, angle.z); 
       break; 
      case Axis.Y: 
       transform.localEulerAngles = new Vector3(angle.x, Rotation(), angle.z); 
       break; 
      case Axis.Z: 
       transform.localEulerAngles = new Vector3(angle.x, angle.y, Rotation()); 
       break; 
     } 
    } 

    float Rotation() 
    { 
     rotation += speed * Time.deltaTime; 
     if (rotation >= 360f) 
      rotation -= 360f; // this will keep it to a value of 0 to 359.99... 
     return direction ? rotation : -rotation; 
    } 
} 

然後,您可以在運行時修改速度,軸和方向以找到適合您的方法。儘管一定要在停止遊戲後重新設置,因爲它不會被保存。

+0

當我改變Y軸和Z軸旋轉時,它們工作正常並繼續旋轉,但X軸上的旋轉停止在90º和-90º。有任何想法嗎? – TrumpetDude

+0

不是沒有看到更多的代碼。我建議接受這個答案,因爲它的確如我所闡述的那樣旋轉。發佈一個新問題。 –

+0

有機會測試這個。使它更完整,但功能保持不變。它適用於所有3軸,無論方向如何。 –

0

您錯過了旋轉中的W組件,並且這導致了代碼中的問題。試試這個:

transform.rotation = Quaternion.Euler(transform.eulerAngles.x, 
             transform.eulerAngles.y + 1.0f, 
             transform.eulerAngles.z); 

而且,看看這些在這裏:

http://answers.unity3d.com/questions/123827/transformrotate-stuck-at-90-and-270-degrees.html http://answers.unity3d.com/questions/187073/rotation-locks-at-90-or-270-degrees.html

我推薦第二個。

+0

像其他答案一樣,除了X軸上的旋轉停止在90º和-90º之外,此工作正常。你知道如何解決這個問題嗎? – TrumpetDude

+0

是的,我做了一些研究,看看這裏:http://answers.unity3d.com/questions/123827/transformrotate-stuck-at-90-and-270-degrees.html和這一個:http://答案。 unity3d.com/questions/187073/rotation-locks-at-90-or-270-degrees.html我重溫第二個 – pasotee

+0

W組件究竟是什麼? – TrumpetDude