- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Rotate : MonoBehaviour {
- private float origionZ;
- private Quaternion targetRotation;
- public float RotateAngle = 60;
- public int count = 0;
- 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 <= 0)
- {
- i = true;
- }
- if (i == true)
- {
- count++;
- targetRotation = Quaternion.Euler(0, 180, RotateAngle * count + origionZ) * Quaternion.identity;
- }
- if(i==false)
- {
- count--;
- targetRotation = Quaternion.Euler(0,180,RotateAngle*count+origionZ) * Quaternion.identity;
- }
- }
- else
- {
- transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2);
- // 避免误差
- if (Quaternion.Angle(targetRotation, transform.rotation) < 1)
- transform.rotation = targetRotation;
- }
- }
- }
使用四元数可以避免万向锁的问题, 并且实现平滑转化. 当按下 D 键时, 物体的 z 轴会旋转 60 度, 在该脚本中, 物体的 Z 轴在 0~180 度之间来回变化, 其中 count 的值可以改变, 造成的结果就是角度范围和旋转次数的变化.
该脚本可适用于 uinty 中需要旋转指示的对象, 如按钮, 把手, 门等物体.
来源: http://www.bubuko.com/infodetail-3101050.html