可指定物体的旋转时间速度停下角度,可以参考来实现转盘抽奖或图片翻转打开等效果。
1 using UnityEngine; 2 using System.Collections; 3 4 public class Rotate : MonoBehaviour 5 { 6 public float targetAngle = 180f; 7 public float spinSpeed = 6f; 8 public float stopSpeed = 2f; 9 public float duration = 3f; 10 float tmpAngle; 11 Vector3 tmpLocalEulerAngles; 12 13 float countdown; 14 float _targetAngle; 15 16 public enum State 17 { 18 Stopped, 19 Spinning, 20 Stopping 21 } 22 23 public State state 24 { 25 get 26 { 27 return _state; 28 } 29 } 30 31 State _state = State.Stopped; 32 33 public void StartSpin () 34 { 35 transform.localEulerAngles = Vector3.zero; 36 _targetAngle = targetAngle % 360f; 37 countdown = duration; 38 _state = State.Spinning; 39 enabled = true; 40 } 41 42 void OnGUI () 43 { 44 if (GUI.Button (new Rect (0f, 0f, 100f, 100f), "Rotate")) { 45 StartSpin (); 46 } 47 } 48 49 void Update () 50 { 51 switch (_state) { 52 case State.Spinning: 53 transform.Rotate (0f, spinSpeed, 0f); 54 countdown -= Time.deltaTime; 55 if (countdown < 0f) { 56 if (transform.localEulerAngles.y > _targetAngle) 57 _targetAngle = 360f - (transform.localEulerAngles.y - _targetAngle) + transform.localEulerAngles.y; 58 tmpAngle = transform.localEulerAngles.y; 59 _state = State.Stopping; 60 } 61 break; 62 case State.Stopping: 63 tmpAngle = Mathf.Lerp (tmpAngle, _targetAngle, Time.deltaTime * stopSpeed); 64 tmpLocalEulerAngles = transform.localEulerAngles; 65 tmpLocalEulerAngles.y = tmpAngle; 66 transform.localEulerAngles = tmpLocalEulerAngles; 67 if (tmpAngle < targetAngle + 0.5f && tmpAngle > targetAngle - 0.5f) { 68 _state = State.Stopped; 69 } 70 break; 71 default: 72 // enabled = false; 73 break; 74 } 75 } 76 }
时间: 2024-09-30 11:41:14