情景描述:Cube的forward箭头如何匀速经过空间中最小角度最终朝向空间任一位置。
Unity的Scene中创建两个Cube,为其中一个挂上下面脚本。
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public Transform target;//将未挂本脚本的Cube拖到此处;
void OnGUI()
{
if(GUILayout.Button("Test"))
{
TweenRotation mytween = GetComponent
();
Vector3 originRotation = transform.eulerAngles;
transform.LookAt(target.position);//先让Cube朝向目标
Vector3 targetRotation = transform.rotation.eulerAngles;//获得目标角度
transform.eulerAngles = originRotation;//再使得Cube变为初始的朝向
mytween.from = originRotation;
//对于X轴方向旋转角的处理
//若在X轴方向的目标角度比当前角度小于180度就将目标角度增加360度,这样目标角度就比当前角度大delta度,delta必定小于180度。
//这样就保证了在旋转时X轴方向需要旋转的角度最小
if(originRotation.x - targetRotation.x > 180 ){
targetRotation = new Vector3(targetRotation.x+360,targetRotation.y,targetRotation.z);
}
//若在X轴方向的目标角度比当前角度大于180度就将目标角度减少360度,这样目标角度就比当前角度小delta度,delta必定小于180度。
else if(originRotation.x - targetRotation.x < -180 ){
targetRotation = new Vector3(targetRotation.x-360,targetRotation.y,targetRotation.z);
}
//对于Y轴方向旋转角的处理
if(originRotation.y - targetRotation.y > 180 )
{
targetRotation = new Vector3(targetRotation.x,targetRotation.y+360,targetRotation.z);
}
else if(originRotation.y - targetRotation.y < -180 )
{
targetRotation = new Vector3(targetRotation.x,targetRotation.y-360,targetRotation.z);
}
//对于Z轴方向旋转角度的处理
if(originRotation.z - targetRotation.z > 180 )
{
targetRotation = new Vector3(targetRotation.x,targetRotation.y,targetRotation.z+360);
}
else if(originRotation.z - targetRotation.z < -180 )
{
targetRotation = new Vector3(targetRotation.x,targetRotation.y,targetRotation.z-360);
}
mytween.to = targetRotation;
mytween.ResetToBeginning();
mytween.Play();
}
}
}