unity中实现物体在一定角度范围内来回旋转
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 }
使用四元数可以避免万向锁的问题,并且实现平滑转化。当按下D键时,物体的z轴会旋转60度,在该脚本中,物体的Z轴在0~180度之间来回变化,其中count的值可以改变,造成的结果就是角度范围和旋转次数的变化。
该脚本可适用于uinty中需要旋转指示的对象,如按钮,把手,门等物体。