Skip to content

Instantly share code, notes, and snippets.

@RandomOutput
Created August 12, 2014 15:24
Show Gist options
  • Select an option

  • Save RandomOutput/84a18279cdbb7d0c893f to your computer and use it in GitHub Desktop.

Select an option

Save RandomOutput/84a18279cdbb7d0c893f to your computer and use it in GitHub Desktop.
pinchbehavior.cs
using UnityEngine;
using System.Collections;
using Leap;
public class PinchBehavior : MonoBehaviour {
[SerializeField]
private float _startPinch = 0.75f;
[SerializeField]
private float _endPinch = 0.5f;
private RigidHand _rigid; //Reference to the Rigid Hand script
private Hand _hand; //Reference to the Latest Leap Motion Hand Object
private HandController _handController; //Reference to the hand controller script
private bool _isPinching = false; //Hold whether or not we're pinching.
private GameObject _pinchedObject;
// Use this for initialization
void Start () {
_pinchedObject = null;
_handController = GameObject.Find("ControllerSandBox").transform.GetComponent<HandController>();
_rigid = transform.GetComponent<RigidHand>();
Debug.Log("_rigid " + _rigid);
Debug.Log("_hand " + _hand);
}
// Update is called once per frame
void Update () {
_hand = _rigid.GetLeapHand(); //Get the most recent hand object
if(_hand == null || _hand == Hand.Invalid) { return; }
Finger index = Finger.Invalid;
Finger thumb = Finger.Invalid;
Vector3 indexPosition;
Vector3 thumbPosition;
Vector3 pinchPoint;
GameObject pinchTarget;
if(_isPinching) {
Debug.Log("is pinching");
foreach(Finger finger in _hand.Fingers) {
if(finger.Type() == Finger.FingerType.TYPE_INDEX) {
index = finger;
}
else if(finger.Type() == Finger.FingerType.TYPE_THUMB) {
thumb = finger;
}
if(index != Finger.Invalid && thumb != Finger.Invalid) {
indexPosition = index.Bone(Bone.BoneType.TYPE_DISTAL).NextJoint.ToUnityScaled();
thumbPosition = index.Bone(Bone.BoneType.TYPE_DISTAL).NextJoint.ToUnityScaled();
pinchPoint = indexPosition + (0.5f * (thumbPosition - indexPosition));
pinchPoint = _handController.transform.TransformPoint(pinchPoint);
if(_pinchedObject == null) {
pinchTarget = getNearestPinchable(pinchPoint);
} else {
pinchTarget = _pinchedObject;
}
pinchTarget.transform.position = pinchPoint;
}
}
if(_hand.PinchStrength <= _endPinch) {
_isPinching = false;
_pinchedObject = null;
}
}
else {
Debug.Log (_hand.PinchStrength);
if(_hand.PinchStrength >= _startPinch) {
_isPinching = true;
}
}
}
GameObject getNearestPinchable(Vector3 targetPosition) {
GameObject retObj = null;
float minDist = float.MaxValue;
GameObject[] pinchables = GameObject.FindGameObjectsWithTag("pinchable");
foreach(GameObject pinchable in pinchables) {
float distance = (targetPosition - pinchable.transform.position).magnitude;
if(distance < minDist) {
retObj = pinchable;
minDist = distance;
}
}
return retObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment