| 1 | using System.Collections; |
| 2 | using System.Collections.Generic; |
| 3 | using UnityEngine; |
| 4 | |
| 5 | public class ObjectGrabber : MonoBehaviour |
| 6 | { |
| 7 | [SerializeField] private Controllers type; |
| 8 | private Grabbable grabbed; |
| 9 | private Transform oldParent; |
| 10 | |
| 11 | private float grabDistance = 0.2f; |
| 12 | |
| 13 | private Vector3 oldPosition = Vector3.zero; |
| 14 | private Vector3 oldRotation; |
| 15 | |
| 16 | public enum Controllers |
| 17 | { |
| 18 | Primary_Left, Secondary_Right |
| 19 | } |
| 20 | |
| 21 | private bool grab = false; |
| 22 | |
| 23 | // Update is called once per frame |
| 24 | void Update() |
| 25 | { |
| 26 | if (grab == false) |
| 27 | { |
| 28 | if(grabbed != null) |
| 29 | { |
| 30 | grabbed.Release((transform.position - oldPosition) * 100, (transform.rotation.eulerAngles - oldRotation) * 2); |
| 31 | grabbed = null; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | if (type == Controllers.Primary_Left) |
| 36 | { |
| 37 | grab = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger) > 0.5f; |
| 38 | } |
| 39 | |
| 40 | if (type == Controllers.Secondary_Right) |
| 41 | { |
| 42 | grab = OVRInput.Get(OVRInput.Axis1D.SecondaryIndexTrigger) > 0.5f; |
| 43 | } |
| 44 | |
| 45 | if (grab && grabbed == null) |
| 46 | { |
| 47 | Grabbable[] bodies = FindObjectsOfType<Grabbable>(); |
| 48 | |
| 49 | Grabbable body = null; |
| 50 | float d = grabDistance; |
| 51 | |
| 52 | for(int i = 0; i < bodies.Length; i++) |
| 53 | { |
| 54 | float dist = Vector3.Distance(transform.position, bodies[i].transform.position); |
| 55 | |
| 56 | if(dist < d) |
| 57 | { |
| 58 | body = bodies[i]; |
| 59 | d = dist; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | grabbed = body; |
| 64 | |
| 65 | if(grabbed != null) |
| 66 | { |
| 67 | grabbed.Grab(this); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | oldPosition = transform.position; |
| 72 | oldRotation = transform.rotation.eulerAngles; |
| 73 | } |
| 74 | } |