| | | 1 | | using System; |
| | | 2 | | using UnityEngine; |
| | | 3 | | using UnityEngine.Events; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Calls events for when the velocity of this objects breaks the begin and end threshold |
| | | 7 | | /// </summary> |
| | | 8 | | [RequireComponent(typeof(Rigidbody))] |
| | | 9 | | public class OnVelocity : MonoBehaviour |
| | | 10 | | { |
| | | 11 | | [Tooltip("The speed calls the begin event")] |
| | 8 | 12 | | public float beginThreshold = 1.25f; |
| | | 13 | | |
| | | 14 | | [Tooltip("The speed calls the end event")] |
| | 8 | 15 | | public float endThreshold = 0.25f; |
| | | 16 | | |
| | | 17 | | [Serializable] public class VelocityEvent : UnityEvent<MonoBehaviour> { } |
| | | 18 | | |
| | | 19 | | // Begin threshold has been broken |
| | 8 | 20 | | public VelocityEvent OnBegin = new VelocityEvent(); |
| | | 21 | | |
| | | 22 | | // End threshold has been broken |
| | 8 | 23 | | public VelocityEvent OnEnd = new VelocityEvent(); |
| | | 24 | | |
| | 8 | 25 | | private Rigidbody rigidBody = null; |
| | 8 | 26 | | private bool hasBegun = false; |
| | | 27 | | |
| | | 28 | | private void Awake() |
| | 4 | 29 | | { |
| | 4 | 30 | | rigidBody = GetComponent<Rigidbody>(); |
| | 4 | 31 | | } |
| | | 32 | | |
| | | 33 | | private void Update() |
| | 11158 | 34 | | { |
| | 11158 | 35 | | CheckVelocity(); |
| | 11158 | 36 | | } |
| | | 37 | | |
| | | 38 | | private void CheckVelocity() |
| | 11158 | 39 | | { |
| | 11158 | 40 | | float speed = rigidBody.velocity.magnitude; |
| | 11158 | 41 | | hasBegun = HasVelocityBegun(speed); |
| | | 42 | | |
| | 11158 | 43 | | if (HasVelcoityEnded(speed)) |
| | 0 | 44 | | Reset(); |
| | 11158 | 45 | | } |
| | | 46 | | |
| | | 47 | | private bool HasVelocityBegun(float speed) |
| | 11158 | 48 | | { |
| | 11158 | 49 | | if (hasBegun) |
| | 2078 | 50 | | return true; |
| | | 51 | | |
| | 9080 | 52 | | bool beginCheck = speed > beginThreshold; |
| | | 53 | | |
| | 9080 | 54 | | if (beginCheck) |
| | 2 | 55 | | OnBegin.Invoke(this); |
| | | 56 | | |
| | 9080 | 57 | | return beginCheck; |
| | 11158 | 58 | | } |
| | | 59 | | |
| | | 60 | | private bool HasVelcoityEnded(float speed) |
| | 11158 | 61 | | { |
| | 11158 | 62 | | if (!hasBegun) |
| | 9078 | 63 | | return false; |
| | | 64 | | |
| | 2080 | 65 | | bool endCheck = speed < endThreshold; |
| | | 66 | | |
| | 2080 | 67 | | if (endCheck) |
| | 0 | 68 | | OnEnd.Invoke(this); |
| | | 69 | | |
| | 2080 | 70 | | return endCheck; |
| | 11158 | 71 | | } |
| | | 72 | | |
| | | 73 | | public void Reset() |
| | 0 | 74 | | { |
| | 0 | 75 | | hasBegun = false; |
| | 0 | 76 | | } |
| | | 77 | | } |