Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTC VIVE controller script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WandController : MonoBehaviour
{
private Valve.VR.EVRButtonId gripButton = Valve.VR.EVRButtonId.k_EButton_Grip;
private Valve.VR.EVRButtonId triggerButton = Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger;
private SteamVR_Controller.Device controller { get { return SteamVR_Controller.Input((int)trackedObj.index); } }
public SteamVR_TrackedObject trackedObj;
HashSet<InteractibleItem> objectsHoveringOver = new HashSet<InteractibleItem>();
private InteractibleItem closestItem;
private InteractibleItem interactingItem;
public bool triggerDown, triggerUp, gripDown, gripUp;
public bool ableToPickup;
// Use this for initialization
void Start()
{
trackedObj = GetComponent<SteamVR_TrackedObject>();
}
// Update is called once per frame
void Update()
{
CheckIfGripDown();
CheckIfGripUp();
CheckIfTriggerDown();
CheckIfTriggerUp();
if (controller == null)
{
Debug.Log("Controller not initialized");
return;
}
if (gripUp)
{
float minDistance = float.MaxValue;
float distance;
foreach (InteractibleItem item in objectsHoveringOver)
{
distance = (item.transform.position - transform.position).sqrMagnitude;
if (distance < minDistance)
{
minDistance = distance;
closestItem = item;
}
}
interactingItem = closestItem;
if (interactingItem && ableToPickup)
{
if (interactingItem.IsInteracting())
{
interactingItem.EndInteraction(this);
}
interactingItem.BeginInteraction(this);
}
gripUp = false;
}
//use to let item fall down
if (gripDown && interactingItem != null)
{
interactingItem.EndInteraction(this);
}
}
private void OnTriggerEnter(Collider collider)
{
InteractibleItem collidedItem = collider.GetComponent<InteractibleItem>();
if (collidedItem)
{
ableToPickup = true;
SteamVR_Controller.Input((int)trackedObj.index).TriggerHapticPulse(1000);
objectsHoveringOver.Add(collidedItem);
}
}
private void OnTriggerExit(Collider collider)
{
InteractibleItem collidedItem = collider.GetComponent<InteractibleItem>();
if (collidedItem)
{
ableToPickup = false;
objectsHoveringOver.Remove(collidedItem);
}
}
//imput checks for tiggers and grip buttons
void CheckIfTriggerDown()
{
if (controller.GetPressDown(triggerButton))
{
triggerDown = true;
triggerUp = false;
}
}
void CheckIfTriggerUp()
{
if (controller.GetPressUp(triggerButton))
{
triggerDown = false;
triggerUp = true;
}
}
void CheckIfGripDown()
{
if (controller.GetPressDown(gripButton))
{
gripDown = true;
gripUp = false;
}
}
void CheckIfGripUp()
{
if (controller.GetPressUp(gripButton))
{
gripDown = false;
gripUp = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.