Unity中實現控制物體以自定義的速度沿Y軸旋轉90度(也可自定義度數)後停止,然後返回原來位置
阿新 • • 發佈:2018-11-07
1、需要控制沿Y軸旋轉的物體,如下所示:
2、編寫控制該物體旋轉的指令碼,如下所示:
using UnityEngine; using System.Collections; public class Test_CycleRoate : MonoBehaviour { public int rotateAngle=90; //旋轉角度 public int rotateSpeed=2; //旋轉速度 private bool isOpen=false; //開啟排風門 private bool isClose=false; //關閉進風門 // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(isOpen) { RotateXOpen(rotateAngle); } if(isClose&&isOpen==false) { RotateXClose(); } } /// <summary> /// 開啟進風門 /// </summary> public void OpenEnterWindDoor() { isOpen=true; Debug.Log("1111"); } /// <summary> /// 關閉進風門 /// </summary> public void CloseEnterWindDoor() { isClose = true; Debug.Log("222"); } /// <summary> /// Rotates the X open. /// </summary> /// <param name="CurentRotateAngle">Curent rotate angle.(預設範圍是0-90度)</param> private void RotateXOpen(int CurentRotateAngleY=90) { if (CurentRotateAngleY > 0 && CurentRotateAngleY <= 90) { Quaternion target=Quaternion.Euler(90,CurentRotateAngleY,0); transform.rotation=Quaternion.RotateTowards(transform.rotation,target,rotateSpeed); if(transform.rotation.eulerAngles.y>=CurentRotateAngleY) { isOpen=!isOpen; Debug.Log(isOpen); } } else { Debug.Log(GetType()+"/CtrlGameObjectRoate()/設定的旋轉角度不在0-90度的範圍內,請重新輸入!!!"); } } /// <summary> /// Rotates the X close. /// </summary> private void RotateXClose() { Quaternion target=Quaternion.Euler(90,0,0); transform.rotation=Quaternion.RotateTowards(transform.rotation,target,rotateSpeed); if(transform.rotation.eulerAngles.y<=0) { isClose=!isClose; Debug.Log(isClose); } } }
3、將該控制指令碼新增給需要控制的物體,然後指定控制的方法給按鈕即可:
四、執行點選對應的按鈕即可實現效果