Unity 使用Quaternions 表示旋转,应小心处理。
我建议你使用Quaternion.Euler,它以简单的角度作为参数。
public float rotationSpeed = 0.01f ;
private Transform child;
private float initialYRotation;
private bool textChanged = false;
private void Awake()
{
child = transform.GetChild(0);
initialYRotation = child.rotation.eulerAngles.y ;
}
private void Update()
{
Quaternion fromRotation = child.rotation ;
Quaternion toRotation = Quaternion.Euler( 0, 180, 0 ) ; // Not the same as new Quaternion(0, 180, 0, 0) !!!
Quaternion rotation = Quaternion.Lerp( fromRotation, toRotation, Time.deltaTime * rotationSpeed );
child.rotation = rotation;
if( !textChanged && Mathf.Abs( child.rotation.eulerAngles.y - initialYRotation ) > 90 )
{
// Change the text
textChanged = true ;
}
}
如果您希望您的对象进行 360° 的完整旋转。四元数不太理想,我想你可以使用Vector3 没有任何问题:
public float rotationSpeed = 0.01f ;
private Transform child;
private float initialYRotation;
private bool textChanged = false;
private void Awake()
{
child = transform.GetChild(0);
initialYRotation = child.rotation.eulerAngles.y ;
}
private void Update()
{
Vector3 fromRotation = child.eulerAngles ;
Vector3 toRotation = new Vector3( 0, 360, 0 ) ;
Vector3 rotation = Vector3.Lerp( fromRotation, toRotation, Time.deltaTime * rotationSpeed );
child.eulerAngles = rotation;
if( !textChanged && Mathf.Abs( rotation.y - initialYRotation ) > 90 )
{
transform.GetChild(0).GetComponent<UnityEngine.UI.Text>().text = "Success";
textChanged = true ;
}
}