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中需要旋轉指示的對象,如按鈕,把手,門等物體。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM