1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class Rotate : MonoBehaviour { 6 private float origionZ; 7 private Quaternion targetRotation; 8 public float RotateAngle = 60; 9 public int count = 0; 10 private bool i; 11 // Use this for initialization 12 void Start () { 13 origionZ = transform.rotation.z; 14 } 15 16 // Update is called once per frame 17 void Update () { 18 if (Input.GetKeyDown(KeyCode.D))//当按下D时进行旋转 19 { 20 if (count >= 3) 21 { 22 i = false; 23 } 24 if (count <= 0) 25 { 26 i = true; 27 } 28 29 if (i == true) 30 { 31 count++; 32 targetRotation = Quaternion.Euler(0, 180, RotateAngle * count + origionZ) * Quaternion.identity; 33 } 34 if(i==false) 35 { 36 count--; 37 targetRotation = Quaternion.Euler(0,180,RotateAngle*count+origionZ) * Quaternion.identity; 38 } 39 40 41 } 42 else 43 { 44 transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2); 45 //避免误差 46 if (Quaternion.Angle(targetRotation, transform.rotation) < 1) 47 transform.rotation = targetRotation; 48 } 49 50 } 51 }
Using quaternions avoid gimbal lock problem, and achieves a smooth conversion. When the D key is pressed, z-axis of the object is rotated 60 degrees, in the script, Z-axis object change back and forth between 0 and 180 degrees, wherein the value of count may vary, the result is that the rotation angle range and change the number.
The script may be applied to a subject in need uinty rotation instruction, such as buttons, knobs, doors, and other objects.