Unity3D-Cube如何匀速经过空间中最小角度最终朝向空间任一位置

情景描述: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();
		}
	}
}

   
   

 
 
运行程序点击Test按钮。看看效果吧。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值