-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrab_Throw.cs
More file actions
91 lines (70 loc) · 2.72 KB
/
Grab_Throw.cs
File metadata and controls
91 lines (70 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grab_Throw : MonoBehaviour
{
private GameObject grabbedObject;
private bool grabbing;
private Quaternion lastRotation, currentRotation;
//public OVRInput.Controller controller;
public string buttonName;
public LayerMask grabMask;
public float grabRadius;
// Update is called once per frame
void Update()
{
//if (!grabbing && Input.GetAxis(buttonName) == 1)
if (!grabbing && Input.GetButtonDown(buttonName))
{
Debug.Log("Trigger Down!");
GrabObject();
}
if (grabbing && Input.GetAxis(buttonName) < 1)
{
DropObject();
}
if (grabbedObject != null)
{
lastRotation = currentRotation;
currentRotation = grabbedObject.transform.rotation;
}
}
void GrabObject()
{
grabbing = true;
RaycastHit[] hits;
hits = Physics.SphereCastAll(transform.position, grabRadius, transform.forward, 0f, grabMask);
if (hits.Length > 0)
{
int closesHit = 0;
for (int i = 0; i < hits.Length; i++)
{
if (hits[i].distance < hits[closesHit].distance)
{
closesHit = i;
}
}
grabbedObject = hits[closesHit].transform.gameObject;
grabbedObject.GetComponent<Rigidbody>().isKinematic = true;
grabbedObject.transform.position = transform.position;
grabbedObject.transform.parent = transform; // Lock grabbed object to the parent i.e. the hand
}
}
void DropObject()
{
grabbing = false;
if (grabbedObject != null)
{
grabbedObject.transform.parent = null;
grabbedObject.GetComponent<Rigidbody>().isKinematic = false;
//grabbedObject.GetComponent<Rigidbody>().velocity = OVRInput.GetLocalControllerVelocity(controller); // Apply the velocity of the hand to the object at release
grabbedObject.GetComponent<Rigidbody>().angularVelocity = GetAngularVelocity();//OVRInput.GetLocalControllerAngularVelocity(controller); // Apply the velocity of the hand to the object at release
grabbedObject = null;
}
}
Vector3 GetAngularVelocity()
{
Quaternion deltaRotation = currentRotation * Quaternion.Inverse(lastRotation);
return new Vector3(Mathf.DeltaAngle(0, deltaRotation.eulerAngles.x), Mathf.DeltaAngle(0, deltaRotation.eulerAngles.y), Mathf.DeltaAngle(0, deltaRotation.eulerAngles.z));
}
}