Skip to content

Instantly share code, notes, and snippets.

@JotaroS
Created May 6, 2017 14:23
Show Gist options
  • Save JotaroS/99a607dec3b15826676e90be8f8c0c0b to your computer and use it in GitHub Desktop.
Save JotaroS/99a607dec3b15826676e90be8f8c0c0b to your computer and use it in GitHub Desktop.
Wanna grab somtin in VR?
using UnityEngine;
using System.Collections;
public class Grab : MonoBehaviour {
public OVRInput.Controller controller;
// Use this for initialization
private GameObject grabbedObject;
private bool grabbing;
public const float THRES_GRAB = 0.55f;
public const float THRES_DROP = 0.35f;
public float grabRadius;
public LayerMask grabMask;
private Quaternion lastRotation, currentRotation;
void Start () {
}
void GrabObject(){
grabbing = true;
RaycastHit[] hits;
hits = Physics.SphereCastAll (transform.position, grabRadius, transform.forward, 0f, grabMask);
if (hits.Length > 0) {
int closestHit = 0;
for (int i = 0; i < hits.Length; i++) {
if (hits [i].distance > hits [closestHit].distance)
closestHit = i;
}
grabbedObject = hits [closestHit].transform.gameObject;
grabbedObject.GetComponent<Rigidbody> ().isKinematic = true;
grabbedObject.transform.position = transform.position;
grabbedObject.transform.parent = transform;
}
}
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));
}
void DropObject(){
grabbing = false;
if (grabbedObject != null) {
grabbedObject.transform.parent = null;
grabbedObject.GetComponent<Rigidbody> ().isKinematic = false;
grabbedObject.GetComponent<Rigidbody> ().velocity = OVRInput.GetLocalControllerVelocity (controller);
//grabbedObject.GetComponent<Rigidbody> ().angularVelocity = GetAngularVelocity();
grabbedObject = null;
}
}
// Update is called once per frame
void Update () {
OVRInput.Update ();
if (grabbedObject != null) {
lastRotation = currentRotation;
currentRotation = grabbedObject.transform.rotation;
}
if (!grabbing && OVRInput.Get (OVRInput.Axis1D.PrimaryHandTrigger, controller) >= THRES_GRAB)
GrabObject ();
if (grabbing && OVRInput.Get (OVRInput.Axis1D.PrimaryHandTrigger, controller) <= THRES_DROP)
DropObject ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment