How to Grab/Throw objects using SteamVR

Rushil Reddy
7/4/2016

Import SteamVR and add in a camera rig to get started.

Now make a cube and set its transform scale to (10,1,10). Add in a sphere as well and its scale to (.5,.5,.5). In the inspector panel, click on Add Component> Rigidbody. In the hierarchy panel click on Controller(Right). It should be a child of Camera Rig if you have trouble finding it. Add a RigidBody component, make sure Use Gravity is unchecked and check IsKinematic. Now add in a sphere collider, select isTrigger and set it's raidus to .15.

Finally, lets Add Component> New Script(C#) and name it GrabObject

using UnityEngine;

using System.Collections;

public class GrabObject : MonoBehaviour

{

public SteamVR_TrackedObject trackedObject;

public SteamVR_Controller.Device device;

public float throwSpeed = 2.0f;

// Use this for initialization void Start()

{ trackedObject = GetComponent();

}

// Update is called once per frame void Update() {

device = SteamVR_Controller.Input((int)trackedObject.index);

}

void OnTriggerStay(Collider col)

{

if (col.tag == "Ball") {

if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger)) {

col.gameObject.GetComponent().isKinematic = true;

col.gameObject.transform.SetParent(gameObject.transform);

}

if (device.GetPressUp(SteamVR_Controller.ButtonMask.Trigger)) {

col.gameObject.GetComponent().isKinematic = false;

col.gameObject.transform.SetParent(null);

TossObject(col.attachedRigidbody);

}

}

}

public void TossObject(Rigidbody rigidBody) {

rigidBody.velocity = device.velocity * throwSpeed;

rigidBody.angularVelocity = device.angularVelocity;

}

Hit Play in the editor and you should be able to grab and throw your sphere.