| | | 1 | | using BNG; |
| | | 2 | | using System; |
| | | 3 | | using UnityEngine; |
| | | 4 | | using System.Diagnostics.CodeAnalysis; |
| | | 5 | | using UnityEngine.Events; |
| | | 6 | | using HenryLab; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// When an object is tilted, run some functionality |
| | | 10 | | /// Used with a grabable object |
| | | 11 | | /// </summary> |
| | | 12 | | public class OnTilt : MonoBehaviour, IGrabbableEntity |
| | | 13 | | { |
| | | 14 | | [ExcludeFromCodeCoverage] |
| | | 15 | | public Grabbable Grabbable |
| | | 16 | | { |
| | | 17 | | get |
| | | 18 | | { |
| | | 19 | | var g = GetComponent<Grabbable>(); |
| | | 20 | | if(g) return g; |
| | | 21 | | return gameObject.AddComponent<Grabbable>(); |
| | | 22 | | } |
| | | 23 | | } |
| | | 24 | | [ExcludeFromCodeCoverage] public string Name => Str.Grabbable; |
| | | 25 | | [ExcludeFromCodeCoverage] public Transform Destination => null; |
| | | 26 | | |
| | | 27 | | [ExcludeFromCodeCoverage] |
| | | 28 | | public void OnGrabbed() |
| | | 29 | | { |
| | | 30 | | } |
| | | 31 | | [ExcludeFromCodeCoverage] |
| | | 32 | | public void OnReleased() |
| | | 33 | | { |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | [Tooltip("Tilt range, 0 - 180 degrees")] |
| | 4 | 37 | | [Range(0, 1)] public float threshold = 0.1f; |
| | | 38 | | |
| | | 39 | | [Serializable] public class TiltEvent : UnityEvent<MonoBehaviour> { } |
| | | 40 | | |
| | | 41 | | // Threshold has been broken |
| | 4 | 42 | | public TiltEvent OnBegin = new TiltEvent(); |
| | | 43 | | |
| | | 44 | | // Threshold is no longer broken |
| | 4 | 45 | | public TiltEvent OnEnd = new TiltEvent(); |
| | | 46 | | |
| | 4 | 47 | | private bool withinThreshold = false; |
| | | 48 | | |
| | | 49 | | private void Update() |
| | 5579 | 50 | | { |
| | 5579 | 51 | | CheckOrientation(); |
| | 5579 | 52 | | } |
| | | 53 | | |
| | | 54 | | private void CheckOrientation() |
| | 5579 | 55 | | { |
| | 5579 | 56 | | float similarity = Vector3.Dot(-transform.up, Vector3.up); |
| | 5579 | 57 | | similarity = Mathf.InverseLerp(0, 1, similarity); |
| | | 58 | | |
| | 5579 | 59 | | bool thresholdCheck = similarity >= threshold; |
| | | 60 | | |
| | 5579 | 61 | | if(withinThreshold != thresholdCheck) |
| | 0 | 62 | | { |
| | 0 | 63 | | withinThreshold = thresholdCheck; |
| | | 64 | | |
| | 0 | 65 | | if(withinThreshold) |
| | 0 | 66 | | { |
| | 0 | 67 | | OnBegin.Invoke(this); |
| | 0 | 68 | | } |
| | | 69 | | else |
| | 0 | 70 | | { |
| | 0 | 71 | | OnEnd.Invoke(this); |
| | 0 | 72 | | } |
| | 0 | 73 | | } |
| | 5579 | 74 | | } |
| | | 75 | | |
| | | 76 | | |
| | | 77 | | |
| | | 78 | | } |