物体旋转后缓慢停在指定角度的实现

Posted 桫椤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了物体旋转后缓慢停在指定角度的实现相关的知识,希望对你有一定的参考价值。

可指定物体的旋转时间速度停下角度,可以参考来实现转盘抽奖或图片翻转打开等效果。

 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 }

 

以上是关于物体旋转后缓慢停在指定角度的实现的主要内容,如果未能解决你的问题,请参考以下文章

Unity3D 控制物体旋转详解 —— 自身绕轴旋转缓慢旋转鼠标控制旋转欧拉数和四元数的关系

SpriteKit 以定义的角度停止旋转***

Unity 相机围绕物体指定观察角度和位置

U3D如何让物体旋转一定角度

Unity获取物体旋转角度怎么计算?

halcon判定物体旋转多少角度