Search code examples
c#unity-game-enginevirtual-reality

Get interacted object in htc Vive


I just start to learn HTC vive app development with unity and want to interact with Object and want to get it as controller interact with it. Try to learning form StreamVR Unity Toolkit documentation. I found a scene in sample demo where Gameobject are interacting through controller but there are so many scripts involved. I am amazed that on a cube VRTK_InteractalbeObject is attached and it is responding to controller. how can i get interacted object in htc vive.?


Solution

  • So, here is one of many solutions to interact with objects with controllers - I will show here the easiest one.

    A. Find [CamerRig] prefab from SteamVR folder and place it in hierarchy: enter image description here

    B. Find Controller (right)->Model GameObject in it:

    enter image description here

    C. Create GameObject with Rigidbody and SphereCollider and place it as child of Controller (right)->Model GameObject

    C.1. Be sure that this object is in same position as Model GameObject

    D. Now play the game, and moving your right vive controller push some other GameObjects that have Rigidbody and any Collider.

    E. To use vive controller Buttons use this script, and place it on Controller (right) GameObject.

    public class VIVEController : MonoBehaviour 
    {
        public SteamVR_TrackedObject trackedObj;
        private SteamVR_Controller.Device controller;
    
        void Start () 
        {
            controller = SteamVR_Controller.Input ((int)trackedObj.index);
        }
    
        void Update ()
        {
            if (controller.GetPressDown (Valve.VR.EVRButtonId.k_EButton_SteamVR_Trigger)) 
            {
                OnTriggerPressed ();
            }
    
            if (controller.GetPressDown (Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad)) 
            {
                OnTouchpadPressed ();
            }
        }
    
        private void OnTriggerPressed()
        {
            Debug.Log("OnTriggerPresse");
        }
    
        private void OnTouchpadPressed()
        {
            Debug.Log("OnTouchpadPressed");
        }
    }
    

    F. Assign from inspector trackedObj (It is on same GameObject as this script)

    G. Find script SteamVR_RenderModel and comment out in method LoadComponents

            for (int i = 0; i < t.childCount; i++)
            {
                var child = t.GetChild(i);
                child.gameObject.SetActive(false);
                StripMesh(child.gameObject);
            }
    

    This is necessary, as otherwise your custom GameObject with collider that is child of controller model, will become inactive.

    Resuming - it is very easy, but you need to do quite few steps. Try playing with controllers buttons, to for instance push object only when you press trigger.

    As bonus, here is small game I made with same approach: https://www.youtube.com/watch?v=kzX7Iw6cHZ8