Unity中实现控制物体以自定义的速度沿Y轴旋转90度(也可自定义度数)后停止,然后返回原来位置

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、将该控制脚本添加给需要控制的物体,然后指定控制的方法给按钮即可:

四、运行点击对应的按钮即可实现效果

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/83345453