using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Rotate : MonoBehaviour {
private float origionZ;
private Quaternion targetRotation;
public float RotateAngle = ;
public int count = ;
private bool i;
// Use this for initialization
void Start () {
origionZ = transform.rotation.z;
} // Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.D))//当按下D时进行旋转
{
if (count >= 3)
{
i = false;
}
if (count <= )
{
i = true;
} if (i == true)
{
count++;
targetRotation = Quaternion.Euler(, , RotateAngle * count + origionZ) * Quaternion.identity;
}
if(i==false)
{
count--;
targetRotation = Quaternion.Euler(,,RotateAngle*count+origionZ) * Quaternion.identity;
} }
else
{
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * );
//避免误差
if (Quaternion.Angle(targetRotation, transform.rotation) < )
transform.rotation = targetRotation;
} }
}

使用四元数可以避免万向锁的问题,并且实现平滑转化。当按下D键时,物体的z轴会旋转60度,在该脚本中,物体的Z轴在0~180度之间来回变化,其中count的值可以改变,造成的结果就是角度范围和旋转次数的变化。

该脚本可适用于uinty中需要旋转指示的对象,如按钮,把手,门等物体。

05-11 22:10