1. 程式人生 > >Unity實現物體沿自身的任意軸向旋轉

Unity實現物體沿自身的任意軸向旋轉

一、建立一個需要旋轉的物體

二、編寫控制該物體的指令碼

using UnityEngine;
using System.Collections;

public class Test_ElectricFan : MonoBehaviour 
{
	public bool isOpen=false;			        //是否開始旋轉
	public int speed=2;					//旋轉的速度


	// Use this for initialization
	void Start () 
	{
	
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(isOpen)
		{

			RotateAxisOfSelf(SelfAxis.Y,speed);
		}

	}

	/// <summary>
	/// 讓物體繞自身的軸旋轉
	/// </summary>
	/// <param name="AxisX">自身的軸</param>
	private void RotateAxisOfSelf(SelfAxis selfAxis,int speed=2)
	{
		switch(selfAxis)
		{
		case SelfAxis.X:
			this.transform.Rotate (new Vector3(1*Time.deltaTime*speed,0,0));
			break;
		case SelfAxis.Y:
			this.transform.Rotate (new Vector3(0,1*Time.deltaTime*speed,0));
			break;
		case SelfAxis.Z:
			this.transform.Rotate (new Vector3(0,0,1*Time.deltaTime*speed));
			break;
		default:
			this.transform.Rotate (new Vector3(1*Time.deltaTime*speed,0,0));
			break;

		}
	
		 
	}



	//列舉軸
	enum SelfAxis
	{
		X,
		Y,
		Z,

	}

}

三、將編寫好的控制物體的指令碼新增給需要沿自身任意軸旋轉的物體上,然後執行程式,接著點選IsOpen打鉤此時物體開始旋轉