Search Unity

Why is My Code Working on PC But Not With VR?

Discussion in 'Scripting' started by FGPArthurVII, Jun 21, 2018.

  1. FGPArthurVII

    FGPArthurVII

    Joined:
    Jan 5, 2015
    Posts:
    106
    Hello. I've been using SteamVR to program a Oculus Rift Simulation.
    So I made a script that states: If I grab an object (considering it has an animation that makes it aim, and in the last bone/joint there is a "burst" as child (A particle system for the water spraying)), the code identifies if It is a fire extinguisher or not. If it is, it animates (Aim the stuff right) and if the burst is not stored, look for it and stores, after that, by pressing B or the Oculus Touch Controller Trigger it Sprays (Activates/unhide/toggle visibility the burst object) so It sprays.

    It works perfectly... On the Computer using Keyboard... but with the Oculus using the touch controls It doens't, I can grab it, but it does not animate nor burst at all.

    After that I modified the StteamVR default "hand" class to call the now implemented functions "ForceBurst ()" and "ForceStop" to try to fix (I imagined that for some reason the normal methods weren't being called through the VR). Still works on the pc but not on VR, same Stuff.

    This is the code to burst and identify the extinguisher:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Valve.VR.InteractionSystem;
    5.  
    6. public class ExtinguisherJet : MonoBehaviour
    7. {
    8.     private Hand hand;
    9.     [SerializeField] GameObject hnd;
    10.     private SteamVR_Controller.Device controller;
    11.     //-----------------------------------------//
    12.     private Transform heldObj;
    13.     private GameObject jet;
    14.     private Animator anim;
    15.     [SerializeField] private GameObject[] extrs;
    16.     [SerializeField] private Transform fbHand;
    17.     GameObject[] bursts;
    18.     private string lasMessage;
    19.     private bool lookForExtinguisher ()
    20.     {
    21.         bool isThere = false;
    22.  
    23.         try
    24.         {
    25.             heldObj = fbHand.transform.GetChild(2);
    26.             isThere = true;
    27.         }
    28.         catch (System.Exception e)
    29.         {
    30.             heldObj = null;
    31.             isThere = false;
    32.         }
    33.         return isThere;
    34.     }
    35.     //--------------------------------------------//
    36.  
    37.     void Start()
    38.     {
    39.         hand = hnd.GetComponent<Hand> ();
    40.  
    41.         bursts = new GameObject[extrs.Length];
    42.         lasMessage = "";
    43.         jet = null;
    44.         anim = null;
    45.     }
    46.        
    47.     private void CheckHand ()
    48.     {
    49.         if (lookForExtinguisher () && lasMessage != heldObj.name)  // lasMessage is Just to Keep the console from printing the same stuff over and over
    50.         {
    51.             print ("Yo, check It out, I got some" + " " + heldObj.name);
    52.  
    53.             if (heldObj.name == "Extinguisher")
    54.             {
    55.                 jet = heldObj.gameObject;
    56.                 for (int i = 1; i < 20; i++)
    57.                     jet = jet.transform.GetChild(0).gameObject;
    58.  
    59.                 print ("Found " + jet.name + " in " + heldObj.name);
    60.                 anim = heldObj.GetComponent <Animator>();
    61.                 anim.SetBool ("willAim", true);
    62.             }
    63.  
    64.             lasMessage = heldObj.name;
    65.  
    66.         } else if (!lookForExtinguisher () && lasMessage != "nothing") {
    67.             print ("Ma boey! Derr's nothin' on yo hands!");
    68.             lasMessage = "nothing";
    69.  
    70.             if (anim != null)
    71.                 anim.SetBool("willAim", false);
    72.         }
    73.     }
    74.  
    75.     private void Bursting ()
    76.     {
    77.         if (lookForExtinguisher ())
    78.         {
    79.             if (heldObj.name == "Extinguisher" && Input.GetKey(KeyCode.B))
    80.             {
    81.                 print ("I'm Bursting");
    82.                 jet.SetActive (true);
    83.             }
    84.             else if (heldObj.name == "Extinguisher" && hand.controller != null && controller.GetHairTriggerDown())
    85.             {
    86.                 print ("I'm Bursting");
    87.                 jet.SetActive(true);
    88.             }
    89.             else if (jet != null)
    90.             {
    91.                 jet.SetActive(false);
    92.             }
    93.         }
    94.     }
    95.  
    96.     public void ForceBurst ()
    97.     {
    98.         if (lookForExtinguisher ())
    99.         {
    100.             if (heldObj.name == "Extinguisher")
    101.             {
    102.                 print ("I'm Bursting");
    103.                 jet.SetActive (true);
    104.             }
    105.             else if (jet != null)
    106.             {
    107.                 jet.SetActive(false);
    108.             }
    109.         }
    110.     }
    111.  
    112.     public void ForceStop()
    113.     {
    114.         SearchforBursting ();
    115.     }
    116.  
    117.     private void SearchforBursting ()
    118.     {
    119.         GameObject tempObj = null;
    120.         GameObject tempJt = null;
    121.         int i = 0;
    122.         int j = 0;
    123.         for (i = 0; i < extrs.Length; i++) //Runs through the Extinguishers' list
    124.         {
    125.             tempObj = extrs[i];
    126.  
    127.             if (bursts[i] == null) //Finds The Burst and stores it, if it isn't stored
    128.             {
    129.                 tempJt = tempObj;
    130.                 for (j = 1; j < 20; j++)
    131.                     tempJt = tempJt.transform.GetChild(0).gameObject;
    132.                 bursts [i] = tempJt;
    133.                 print ("A burst has been stored");
    134.             }
    135.             if (bursts[i].activeSelf && heldObj != tempObj.transform)  //Deactivate them if they are activated if they're not being held
    136.             {
    137.                 bursts[i].SetActive(false);
    138.                 print ("Deactivated");
    139.                 print (heldObj + ", " + tempObj);
    140.             }
    141.         }
    142.     }
    143.  
    144.     void Update ()
    145.     {
    146.         if (hand.controller != null)
    147.         {
    148.             controller = SteamVR_Controller.Input((int) hand.controller.index);
    149.         }
    150.  
    151.         CheckHand ();
    152.         Bursting ();
    153.         SearchforBursting ();
    154.     }
    155. }
    And this is the Default Hand SteamVR class (note that I also modified the Grab object key from the Trigger to the Grip button, minor change, made previously, this works, but the bursting in the other hand does not) with the call to the ForceBurst() and ForceStop().

    Code (CSharp):
    1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
    2. //
    3. // Purpose: The hands used by the player in the vr interaction system
    4. //
    5. //=============================================================================
    6.  
    7. using UnityEngine;
    8. using System;
    9. using System.Collections;
    10. using System.Collections.Generic;
    11. using System.Collections.ObjectModel;
    12.  
    13. namespace Valve.VR.InteractionSystem
    14. {
    15.     //-------------------------------------------------------------------------
    16.     // Links with an appropriate SteamVR controller and facilitates
    17.     // interactions with objects in the virtual world.
    18.     //-------------------------------------------------------------------------
    19.     public class Hand : MonoBehaviour
    20.     {
    21.         public enum HandType
    22.         {
    23.             Left,
    24.             Right,
    25.             Any
    26.         };
    27.  
    28.         // The flags used to determine how an object is attached to the hand.
    29.         [Flags]
    30.         public enum AttachmentFlags
    31.         {
    32.             SnapOnAttach = 1 << 0, // The object should snap to the position of the specified attachment point on the hand.
    33.             DetachOthers = 1 << 1, // Other objects attached to this hand will be detached.
    34.             DetachFromOtherHand = 1 << 2, // This object will be detached from the other hand.
    35.             ParentToHand = 1 << 3, // The object will be parented to the hand.
    36.         };
    37.  
    38.         public const AttachmentFlags defaultAttachmentFlags = AttachmentFlags.ParentToHand |
    39.                                                               AttachmentFlags.DetachOthers |
    40.                                                               AttachmentFlags.DetachFromOtherHand |
    41.                                                               AttachmentFlags.SnapOnAttach;
    42.  
    43.         public Hand otherHand;
    44.         public HandType startingHandType;
    45.  
    46.         public ExtinguisherJet exjet; //Let's use the Extinguisher class I made, shall we.
    47.  
    48.         public Transform hoverSphereTransform;
    49.         public float hoverSphereRadius = 0.05f;
    50.         public LayerMask hoverLayerMask = -1;
    51.         public float hoverUpdateInterval = 0.1f;
    52.  
    53.         public Camera noSteamVRFallbackCamera;
    54.         public float noSteamVRFallbackMaxDistanceNoItem = 10.0f;
    55.         public float noSteamVRFallbackMaxDistanceWithItem = 0.5f;
    56.         private float noSteamVRFallbackInteractorDistance = -1.0f;
    57.  
    58.         public SteamVR_Controller.Device controller;
    59.  
    60.         public GameObject controllerPrefab;
    61.         private GameObject controllerObject = null;
    62.  
    63.         public bool showDebugText = false;
    64.         public bool spewDebugText = false;
    65.  
    66.         public struct AttachedObject
    67.         {
    68.             public GameObject attachedObject;
    69.             public GameObject originalParent;
    70.             public bool isParentedToHand;
    71.         }
    72.  
    73.         private List<AttachedObject> attachedObjects = new List<AttachedObject>();
    74.  
    75.         public ReadOnlyCollection<AttachedObject> AttachedObjects
    76.         {
    77.             get { return attachedObjects.AsReadOnly(); }
    78.         }
    79.  
    80.         public bool hoverLocked { get; private set; }
    81.  
    82.         private Interactable _hoveringInteractable;
    83.  
    84.         private TextMesh debugText;
    85.         private int prevOverlappingColliders = 0;
    86.  
    87.         private const int ColliderArraySize = 16;
    88.         private Collider[] overlappingColliders;
    89.  
    90.         private Player playerInstance;
    91.  
    92.         private GameObject applicationLostFocusObject;
    93.  
    94.         SteamVR_Events.Action inputFocusAction;
    95.  
    96.  
    97.         //-------------------------------------------------
    98.         // The Interactable object this Hand is currently hovering over
    99.         //-------------------------------------------------
    100.         public Interactable hoveringInteractable
    101.         {
    102.             get { return _hoveringInteractable; }
    103.             set
    104.             {
    105.                 if ( _hoveringInteractable != value )
    106.                 {
    107.                     if ( _hoveringInteractable != null )
    108.                     {
    109.                         HandDebugLog( "HoverEnd " + _hoveringInteractable.gameObject );
    110.                         _hoveringInteractable.SendMessage( "OnHandHoverEnd", this, SendMessageOptions.DontRequireReceiver );
    111.  
    112.                         //Note: The _hoveringInteractable can change after sending the OnHandHoverEnd message so we need to check it again before broadcasting this message
    113.                         if ( _hoveringInteractable != null )
    114.                         {
    115.                             this.BroadcastMessage( "OnParentHandHoverEnd", _hoveringInteractable, SendMessageOptions.DontRequireReceiver ); // let objects attached to the hand know that a hover has ended
    116.                         }
    117.                     }
    118.  
    119.                     _hoveringInteractable = value;
    120.  
    121.                     if ( _hoveringInteractable != null )
    122.                     {
    123.                         HandDebugLog( "HoverBegin " + _hoveringInteractable.gameObject );
    124.                         _hoveringInteractable.SendMessage( "OnHandHoverBegin", this, SendMessageOptions.DontRequireReceiver );
    125.  
    126.                         //Note: The _hoveringInteractable can change after sending the OnHandHoverBegin message so we need to check it again before broadcasting this message
    127.                         if ( _hoveringInteractable != null )
    128.                         {
    129.                             this.BroadcastMessage( "OnParentHandHoverBegin", _hoveringInteractable, SendMessageOptions.DontRequireReceiver ); // let objects attached to the hand know that a hover has begun
    130.                         }
    131.                     }
    132.                 }
    133.             }
    134.         }
    135.  
    136.  
    137.         //-------------------------------------------------
    138.         // Active GameObject attached to this Hand
    139.         //-------------------------------------------------
    140.         public GameObject currentAttachedObject
    141.         {
    142.             get
    143.             {
    144.                 CleanUpAttachedObjectStack();
    145.  
    146.                 if ( attachedObjects.Count > 0 )
    147.                 {
    148.                     return attachedObjects[attachedObjects.Count - 1].attachedObject;
    149.                 }
    150.  
    151.                 return null;
    152.             }
    153.         }
    154.  
    155.  
    156.         //-------------------------------------------------
    157.         public Transform GetAttachmentTransform( string attachmentPoint = "" )
    158.         {
    159.             Transform attachmentTransform = null;
    160.  
    161.             if ( !string.IsNullOrEmpty( attachmentPoint ) )
    162.             {
    163.                 attachmentTransform = transform.Find( attachmentPoint );
    164.             }
    165.  
    166.             if ( !attachmentTransform )
    167.             {
    168.                 attachmentTransform = this.transform;
    169.             }
    170.  
    171.             return attachmentTransform;
    172.         }
    173.  
    174.  
    175.         //-------------------------------------------------
    176.         // Guess the type of this Hand
    177.         //
    178.         // If startingHandType is Hand.Left or Hand.Right, returns startingHandType.
    179.         // If otherHand is non-null and both Hands are linked to controllers, returns
    180.         // Hand.Left if this Hand is leftmost relative to the HMD, otherwise Hand.Right.
    181.         // Otherwise, returns Hand.Any
    182.         //-------------------------------------------------
    183.         public HandType GuessCurrentHandType()
    184.         {
    185.             if ( startingHandType == HandType.Left || startingHandType == HandType.Right )
    186.             {
    187.                 return startingHandType;
    188.             }
    189.  
    190.             if ( startingHandType == HandType.Any && otherHand != null && otherHand.controller == null )
    191.             {
    192.                 return HandType.Right;
    193.             }
    194.  
    195.             if ( controller == null || otherHand == null || otherHand.controller == null )
    196.             {
    197.                 return startingHandType;
    198.             }
    199.  
    200.             if ( controller.index == SteamVR_Controller.GetDeviceIndex( SteamVR_Controller.DeviceRelation.Leftmost ) )
    201.             {
    202.                 return HandType.Left;
    203.             }
    204.  
    205.             return HandType.Right;
    206.         }
    207.  
    208.  
    209.         //-------------------------------------------------
    210.         // Attach a GameObject to this GameObject
    211.         //
    212.         // objectToAttach - The GameObject to attach
    213.         // flags - The flags to use for attaching the object
    214.         // attachmentPoint - Name of the GameObject in the hierarchy of this Hand which should act as the attachment point for this GameObject
    215.         //-------------------------------------------------
    216.         public void AttachObject( GameObject objectToAttach, AttachmentFlags flags = defaultAttachmentFlags, string attachmentPoint = "" )
    217.         {
    218.             if ( flags == 0 )
    219.             {
    220.                 flags = defaultAttachmentFlags;
    221.             }
    222.  
    223.             //Make sure top object on stack is non-null
    224.             CleanUpAttachedObjectStack();
    225.  
    226.             //Detach the object if it is already attached so that it can get re-attached at the top of the stack
    227.             DetachObject( objectToAttach );
    228.  
    229.             //Detach from the other hand if requested
    230.             if ( ( ( flags & AttachmentFlags.DetachFromOtherHand ) == AttachmentFlags.DetachFromOtherHand ) && otherHand )
    231.             {
    232.                 otherHand.DetachObject( objectToAttach );
    233.             }
    234.  
    235.             if ( ( flags & AttachmentFlags.DetachOthers ) == AttachmentFlags.DetachOthers )
    236.             {
    237.                 //Detach all the objects from the stack
    238.                 while ( attachedObjects.Count > 0 )
    239.                 {
    240.                     DetachObject( attachedObjects[0].attachedObject );
    241.                 }
    242.             }
    243.  
    244.             if ( currentAttachedObject )
    245.             {
    246.                 currentAttachedObject.SendMessage( "OnHandFocusLost", this, SendMessageOptions.DontRequireReceiver );
    247.             }
    248.  
    249.             AttachedObject attachedObject = new AttachedObject();
    250.             attachedObject.attachedObject = objectToAttach;
    251.             attachedObject.originalParent = objectToAttach.transform.parent != null ? objectToAttach.transform.parent.gameObject : null;
    252.             if ( ( flags & AttachmentFlags.ParentToHand ) == AttachmentFlags.ParentToHand )
    253.             {
    254.                 //Parent the object to the hand
    255.                 objectToAttach.transform.parent = GetAttachmentTransform( attachmentPoint );
    256.                 attachedObject.isParentedToHand = true;
    257.             }
    258.             else
    259.             {
    260.                 attachedObject.isParentedToHand = false;
    261.             }
    262.             attachedObjects.Add( attachedObject );
    263.  
    264.             if ( ( flags & AttachmentFlags.SnapOnAttach ) == AttachmentFlags.SnapOnAttach )
    265.             {
    266.                 objectToAttach.transform.localPosition = Vector3.zero;
    267.                 objectToAttach.transform.localRotation = Quaternion.identity;
    268.             }
    269.  
    270.             HandDebugLog( "AttachObject " + objectToAttach );
    271.             objectToAttach.SendMessage( "OnAttachedToHand", this, SendMessageOptions.DontRequireReceiver );
    272.  
    273.             UpdateHovering();
    274.         }
    275.  
    276.  
    277.         //-------------------------------------------------
    278.         // Detach this GameObject from the attached object stack of this Hand
    279.         //
    280.         // objectToDetach - The GameObject to detach from this Hand
    281.         //-------------------------------------------------
    282.         public void DetachObject( GameObject objectToDetach, bool restoreOriginalParent = true )
    283.         {
    284.             int index = attachedObjects.FindIndex( l => l.attachedObject == objectToDetach );
    285.             if ( index != -1 )
    286.             {
    287.                 HandDebugLog( "DetachObject " + objectToDetach );
    288.  
    289.                 GameObject prevTopObject = currentAttachedObject;
    290.  
    291.                 Transform parentTransform = null;
    292.                 if ( attachedObjects[index].isParentedToHand )
    293.                 {
    294.                     if ( restoreOriginalParent && ( attachedObjects[index].originalParent != null ) )
    295.                     {
    296.                         parentTransform = attachedObjects[index].originalParent.transform;
    297.                     }
    298.                     attachedObjects[index].attachedObject.transform.parent = parentTransform;
    299.                 }
    300.  
    301.                 attachedObjects[index].attachedObject.SetActive( true );
    302.                 attachedObjects[index].attachedObject.SendMessage( "OnDetachedFromHand", this, SendMessageOptions.DontRequireReceiver );
    303.                 attachedObjects.RemoveAt( index );
    304.  
    305.                 GameObject newTopObject = currentAttachedObject;
    306.  
    307.                 //Give focus to the top most object on the stack if it changed
    308.                 if ( newTopObject != null && newTopObject != prevTopObject )
    309.                 {
    310.                     newTopObject.SetActive( true );
    311.                     newTopObject.SendMessage( "OnHandFocusAcquired", this, SendMessageOptions.DontRequireReceiver );
    312.                 }
    313.             }
    314.  
    315.             CleanUpAttachedObjectStack();
    316.         }
    317.  
    318.  
    319.         //-------------------------------------------------
    320.         // Get the world velocity of the VR Hand.
    321.         // Note: controller velocity value only updates on controller events (Button but and down) so good for throwing
    322.         //-------------------------------------------------
    323.         public Vector3 GetTrackedObjectVelocity()
    324.         {
    325.             if ( controller != null )
    326.             {
    327.                 return transform.parent.TransformVector( controller.velocity );
    328.             }
    329.  
    330.             return Vector3.zero;
    331.         }
    332.  
    333.  
    334.         //-------------------------------------------------
    335.         // Get the world angular velocity of the VR Hand.
    336.         // Note: controller velocity value only updates on controller events (Button but and down) so good for throwing
    337.         //-------------------------------------------------
    338.         public Vector3 GetTrackedObjectAngularVelocity()
    339.         {
    340.             if ( controller != null )
    341.             {
    342.                 return transform.parent.TransformVector( controller.angularVelocity );
    343.             }
    344.  
    345.             return Vector3.zero;
    346.         }
    347.  
    348.  
    349.         //-------------------------------------------------
    350.         private void CleanUpAttachedObjectStack()
    351.         {
    352.             attachedObjects.RemoveAll( l => l.attachedObject == null );
    353.         }
    354.  
    355.  
    356.         //-------------------------------------------------
    357.         void Awake()
    358.         {
    359.             inputFocusAction = SteamVR_Events.InputFocusAction( OnInputFocus );
    360.  
    361.             if ( hoverSphereTransform == null )
    362.             {
    363.                 hoverSphereTransform = this.transform;
    364.             }
    365.  
    366.             applicationLostFocusObject = new GameObject( "_application_lost_focus" );
    367.             applicationLostFocusObject.transform.parent = transform;
    368.             applicationLostFocusObject.SetActive( false );
    369.         }
    370.  
    371.  
    372.         //-------------------------------------------------
    373.         IEnumerator Start()
    374.         {
    375.             // save off player instance
    376.             playerInstance = Player.instance;
    377.             if ( !playerInstance )
    378.             {
    379.                 Debug.LogError( "No player instance found in Hand Start()" );
    380.             }
    381.  
    382.             // allocate array for colliders
    383.             overlappingColliders = new Collider[ColliderArraySize];
    384.  
    385.             // We are a "no SteamVR fallback hand" if we have this camera set
    386.             // we'll use the right mouse to look around and left mouse to interact
    387.             // - don't need to find the device
    388.             if ( noSteamVRFallbackCamera )
    389.             {
    390.                 yield break;
    391.             }
    392.  
    393.             //Debug.Log( "Hand - initializing connection routine" );
    394.  
    395.             // Acquire the correct device index for the hand we want to be
    396.             // Also for the other hand if we get there first
    397.             while ( true )
    398.             {
    399.                 // Don't need to run this every frame
    400.                 yield return new WaitForSeconds( 1.0f );
    401.  
    402.                 // We have a controller now, break out of the loop!
    403.                 if ( controller != null )
    404.                     break;
    405.  
    406.                 //Debug.Log( "Hand - checking controllers..." );
    407.  
    408.                 // Initialize both hands simultaneously
    409.                 if ( startingHandType == HandType.Left || startingHandType == HandType.Right )
    410.                 {
    411.                     // Left/right relationship.
    412.                     // Wait until we have a clear unique left-right relationship to initialize.
    413.                     int leftIndex = SteamVR_Controller.GetDeviceIndex( SteamVR_Controller.DeviceRelation.Leftmost );
    414.                     int rightIndex = SteamVR_Controller.GetDeviceIndex( SteamVR_Controller.DeviceRelation.Rightmost );
    415.                     if ( leftIndex == -1 || rightIndex == -1 || leftIndex == rightIndex )
    416.                     {
    417.                         //Debug.Log( string.Format( "...Left/right hand relationship not yet established: leftIndex={0}, rightIndex={1}", leftIndex, rightIndex ) );
    418.                         continue;
    419.                     }
    420.  
    421.                     int myIndex = ( startingHandType == HandType.Right ) ? rightIndex : leftIndex;
    422.                     int otherIndex = ( startingHandType == HandType.Right ) ? leftIndex : rightIndex;
    423.  
    424.                     InitController( myIndex );
    425.                     if ( otherHand )
    426.                     {
    427.                         otherHand.InitController( otherIndex );
    428.                     }
    429.                 }
    430.                 else
    431.                 {
    432.                     // No left/right relationship. Just wait for a connection
    433.  
    434.                     var vr = SteamVR.instance;
    435.                     for ( int i = 0; i < Valve.VR.OpenVR.k_unMaxTrackedDeviceCount; i++ )
    436.                     {
    437.                         if ( vr.hmd.GetTrackedDeviceClass( (uint)i ) != Valve.VR.ETrackedDeviceClass.Controller )
    438.                         {
    439.                             //Debug.Log( string.Format( "Hand - device {0} is not a controller", i ) );
    440.                             continue;
    441.                         }
    442.  
    443.                         var device = SteamVR_Controller.Input( i );
    444.                         if ( !device.valid )
    445.                         {
    446.                             //Debug.Log( string.Format( "Hand - device {0} is not valid", i ) );
    447.                             continue;
    448.                         }
    449.  
    450.                         if ( ( otherHand != null ) && ( otherHand.controller != null ) )
    451.                         {
    452.                             // Other hand is using this index, so we cannot use it.
    453.                             if ( i == (int)otherHand.controller.index )
    454.                             {
    455.                                 //Debug.Log( string.Format( "Hand - device {0} is owned by the other hand", i ) );
    456.                                 continue;
    457.                             }
    458.                         }
    459.  
    460.                         InitController( i );
    461.                     }
    462.                 }
    463.             }
    464.         }
    465.  
    466.  
    467.         //-------------------------------------------------
    468.         private void UpdateHovering()
    469.         {
    470.             if ( ( noSteamVRFallbackCamera == null ) && ( controller == null ) )
    471.             {
    472.                 return;
    473.             }
    474.  
    475.             if ( hoverLocked )
    476.                 return;
    477.  
    478.             if ( applicationLostFocusObject.activeSelf )
    479.                 return;
    480.  
    481.             float closestDistance = float.MaxValue;
    482.             Interactable closestInteractable = null;
    483.  
    484.             // Pick the closest hovering
    485.             float flHoverRadiusScale = playerInstance.transform.lossyScale.x;
    486.             float flScaledSphereRadius = hoverSphereRadius * flHoverRadiusScale;
    487.  
    488.             // if we're close to the floor, increase the radius to make things easier to pick up
    489.             float handDiff = Mathf.Abs( transform.position.y - playerInstance.trackingOriginTransform.position.y );
    490.             float boxMult = Util.RemapNumberClamped( handDiff, 0.0f, 0.5f * flHoverRadiusScale, 5.0f, 1.0f ) * flHoverRadiusScale;
    491.  
    492.             // null out old vals
    493.             for ( int i = 0; i < overlappingColliders.Length; ++i )
    494.             {
    495.                 overlappingColliders[i] = null;
    496.             }
    497.  
    498.             Physics.OverlapBoxNonAlloc(
    499.                 hoverSphereTransform.position - new Vector3( 0, flScaledSphereRadius * boxMult - flScaledSphereRadius, 0 ),
    500.                 new Vector3( flScaledSphereRadius, flScaledSphereRadius * boxMult * 2.0f, flScaledSphereRadius ),
    501.                 overlappingColliders,
    502.                 Quaternion.identity,
    503.                 hoverLayerMask.value
    504.             );
    505.  
    506.             // DebugVar
    507.             int iActualColliderCount = 0;
    508.  
    509.             foreach ( Collider collider in overlappingColliders )
    510.             {
    511.                 if ( collider == null )
    512.                     continue;
    513.  
    514.                 Interactable contacting = collider.GetComponentInParent<Interactable>();
    515.  
    516.                 // Yeah, it's null, skip
    517.                 if ( contacting == null )
    518.                     continue;
    519.  
    520.                 // Ignore this collider for hovering
    521.                 IgnoreHovering ignore = collider.GetComponent<IgnoreHovering>();
    522.                 if ( ignore != null )
    523.                 {
    524.                     if ( ignore.onlyIgnoreHand == null || ignore.onlyIgnoreHand == this )
    525.                     {
    526.                         continue;
    527.                     }
    528.                 }
    529.  
    530.                 // Can't hover over the object if it's attached
    531.                 if ( attachedObjects.FindIndex( l => l.attachedObject == contacting.gameObject ) != -1 )
    532.                     continue;
    533.  
    534.                 // Occupied by another hand, so we can't touch it
    535.                 if ( otherHand && otherHand.hoveringInteractable == contacting )
    536.                     continue;
    537.  
    538.                 // Best candidate so far...
    539.                 float distance = Vector3.Distance( contacting.transform.position, hoverSphereTransform.position );
    540.                 if ( distance < closestDistance )
    541.                 {
    542.                     closestDistance = distance;
    543.                     closestInteractable = contacting;
    544.                 }
    545.                 iActualColliderCount++;
    546.             }
    547.  
    548.             // Hover on this one
    549.             hoveringInteractable = closestInteractable;
    550.  
    551.             if ( iActualColliderCount > 0 && iActualColliderCount != prevOverlappingColliders )
    552.             {
    553.                 prevOverlappingColliders = iActualColliderCount;
    554.                 HandDebugLog( "Found " + iActualColliderCount + " overlapping colliders." );
    555.             }
    556.         }
    557.  
    558.  
    559.         //-------------------------------------------------
    560.         private void UpdateNoSteamVRFallback()
    561.         {
    562.             if ( noSteamVRFallbackCamera )
    563.             {
    564.                 Ray ray = noSteamVRFallbackCamera.ScreenPointToRay( Input.mousePosition );
    565.  
    566.                 if ( attachedObjects.Count > 0 )
    567.                 {
    568.                     // Holding down the mouse:
    569.                     // move around a fixed distance from the camera
    570.                     transform.position = ray.origin + noSteamVRFallbackInteractorDistance * ray.direction;
    571.                 }
    572.                 else
    573.                 {
    574.                     // Not holding down the mouse:
    575.                     // cast out a ray to see what we should mouse over
    576.  
    577.                     // Don't want to hit the hand and anything underneath it
    578.                     // So move it back behind the camera when we do the raycast
    579.                     Vector3 oldPosition = transform.position;
    580.                     transform.position = noSteamVRFallbackCamera.transform.forward * ( -1000.0f );
    581.  
    582.                     RaycastHit raycastHit;
    583.                     if ( Physics.Raycast( ray, out raycastHit, noSteamVRFallbackMaxDistanceNoItem ) )
    584.                     {
    585.                         transform.position = raycastHit.point;
    586.  
    587.                         // Remember this distance in case we click and drag the mouse
    588.                         noSteamVRFallbackInteractorDistance = Mathf.Min( noSteamVRFallbackMaxDistanceNoItem, raycastHit.distance );
    589.                     }
    590.                     else if ( noSteamVRFallbackInteractorDistance > 0.0f )
    591.                     {
    592.                         // Move it around at the distance we last had a hit
    593.                         transform.position = ray.origin + Mathf.Min( noSteamVRFallbackMaxDistanceNoItem, noSteamVRFallbackInteractorDistance ) * ray.direction;
    594.                     }
    595.                     else
    596.                     {
    597.                         // Didn't hit, just leave it where it was
    598.                         transform.position = oldPosition;
    599.                     }
    600.                 }
    601.             }
    602.         }
    603.  
    604.  
    605.         //-------------------------------------------------
    606.         private void UpdateDebugText()
    607.         {
    608.             if ( showDebugText )
    609.             {
    610.                 if ( debugText == null )
    611.                 {
    612.                     debugText = new GameObject( "_debug_text" ).AddComponent<TextMesh>();
    613.                     debugText.fontSize = 120;
    614.                     debugText.characterSize = 0.001f;
    615.                     debugText.transform.parent = transform;
    616.  
    617.                     debugText.transform.localRotation = Quaternion.Euler( 90.0f, 0.0f, 0.0f );
    618.                 }
    619.  
    620.                 if ( GuessCurrentHandType() == HandType.Right )
    621.                 {
    622.                     debugText.transform.localPosition = new Vector3( -0.05f, 0.0f, 0.0f );
    623.                     debugText.alignment = TextAlignment.Right;
    624.                     debugText.anchor = TextAnchor.UpperRight;
    625.                 }
    626.                 else
    627.                 {
    628.                     debugText.transform.localPosition = new Vector3( 0.05f, 0.0f, 0.0f );
    629.                     debugText.alignment = TextAlignment.Left;
    630.                     debugText.anchor = TextAnchor.UpperLeft;
    631.                 }
    632.  
    633.                 debugText.text = string.Format(
    634.                     "Hovering: {0}\n" +
    635.                     "Hover Lock: {1}\n" +
    636.                     "Attached: {2}\n" +
    637.                     "Total Attached: {3}\n" +
    638.                     "Type: {4}\n",
    639.                     ( hoveringInteractable ? hoveringInteractable.gameObject.name : "null" ),
    640.                     hoverLocked,
    641.                     ( currentAttachedObject ? currentAttachedObject.name : "null" ),
    642.                     attachedObjects.Count,
    643.                     GuessCurrentHandType().ToString() );
    644.             }
    645.             else
    646.             {
    647.                 if ( debugText != null )
    648.                 {
    649.                     Destroy( debugText.gameObject );
    650.                 }
    651.             }
    652.         }
    653.  
    654.  
    655.         //-------------------------------------------------
    656.         void OnEnable()
    657.         {
    658.             inputFocusAction.enabled = true;
    659.  
    660.             // Stagger updates between hands
    661.             float hoverUpdateBegin = ( ( otherHand != null ) && ( otherHand.GetInstanceID() < GetInstanceID() ) ) ? ( 0.5f * hoverUpdateInterval ) : ( 0.0f );
    662.             InvokeRepeating( "UpdateHovering", hoverUpdateBegin, hoverUpdateInterval );
    663.             InvokeRepeating( "UpdateDebugText", hoverUpdateBegin, hoverUpdateInterval );
    664.         }
    665.  
    666.  
    667.         //-------------------------------------------------
    668.         void OnDisable()
    669.         {
    670.             inputFocusAction.enabled = false;
    671.  
    672.             CancelInvoke();
    673.         }
    674.  
    675.  
    676.         //-------------------------------------------------
    677.         void Update()
    678.         {
    679.             UpdateNoSteamVRFallback();
    680.  
    681.             GameObject attached = currentAttachedObject;
    682.             if ( attached )
    683.             {
    684.                 attached.SendMessage( "HandAttachedUpdate", this, SendMessageOptions.DontRequireReceiver );
    685.             }
    686.  
    687.             if ( hoveringInteractable )
    688.             {
    689.                 hoveringInteractable.SendMessage( "HandHoverUpdate", this, SendMessageOptions.DontRequireReceiver );
    690.             }
    691.         }
    692.  
    693.  
    694.         //-------------------------------------------------
    695.         void LateUpdate()
    696.         {
    697.             //Re-attach the controller if nothing else is attached to the hand
    698.             if ( controllerObject != null && attachedObjects.Count == 0 )
    699.             {
    700.                 AttachObject( controllerObject );
    701.             }
    702.         }
    703.  
    704.  
    705.         //-------------------------------------------------
    706.         private void OnInputFocus( bool hasFocus )
    707.         {
    708.             if ( hasFocus )
    709.             {
    710.                 DetachObject( applicationLostFocusObject, true );
    711.                 applicationLostFocusObject.SetActive( false );
    712.                 UpdateHandPoses();
    713.                 UpdateHovering();
    714.                 BroadcastMessage( "OnParentHandInputFocusAcquired", SendMessageOptions.DontRequireReceiver );
    715.             }
    716.             else
    717.             {
    718.                 applicationLostFocusObject.SetActive( true );
    719.                 AttachObject( applicationLostFocusObject, AttachmentFlags.ParentToHand );
    720.                 BroadcastMessage( "OnParentHandInputFocusLost", SendMessageOptions.DontRequireReceiver );
    721.             }
    722.         }
    723.  
    724.  
    725.         //-------------------------------------------------
    726.         void FixedUpdate()
    727.         {
    728.             UpdateHandPoses();
    729.         }
    730.  
    731.  
    732.         //-------------------------------------------------
    733.         void OnDrawGizmos()
    734.         {
    735.             Gizmos.color = new Color( 0.5f, 1.0f, 0.5f, 0.9f );
    736.             Transform sphereTransform = hoverSphereTransform ? hoverSphereTransform : this.transform;
    737.             Gizmos.DrawWireSphere( sphereTransform.position, hoverSphereRadius );
    738.         }
    739.  
    740.  
    741.         //-------------------------------------------------
    742.         private void HandDebugLog( string msg )
    743.         {
    744.             if ( spewDebugText )
    745.             {
    746.                 Debug.Log( "Hand (" + this.name + "): " + msg );
    747.             }
    748.         }
    749.  
    750.  
    751.         //-------------------------------------------------
    752.         private void UpdateHandPoses()
    753.         {
    754.             if ( controller != null )
    755.             {
    756.                 SteamVR vr = SteamVR.instance;
    757.                 if ( vr != null )
    758.                 {
    759.                     var pose = new Valve.VR.TrackedDevicePose_t();
    760.                     var gamePose = new Valve.VR.TrackedDevicePose_t();
    761.                     var err = vr.compositor.GetLastPoseForTrackedDeviceIndex( controller.index, ref pose, ref gamePose );
    762.                     if ( err == Valve.VR.EVRCompositorError.None )
    763.                     {
    764.                         var t = new SteamVR_Utils.RigidTransform( gamePose.mDeviceToAbsoluteTracking );
    765.                         transform.localPosition = t.pos;
    766.                         transform.localRotation = t.rot;
    767.                     }
    768.                 }
    769.             }
    770.         }
    771.  
    772.  
    773.         //-------------------------------------------------
    774.         // Continue to hover over this object indefinitely, whether or not the Hand moves out of its interaction trigger volume.
    775.         //
    776.         // interactable - The Interactable to hover over indefinitely.
    777.         //-------------------------------------------------
    778.         public void HoverLock( Interactable interactable )
    779.         {
    780.             HandDebugLog( "HoverLock " + interactable );
    781.             hoverLocked = true;
    782.             hoveringInteractable = interactable;
    783.         }
    784.  
    785.  
    786.         //-------------------------------------------------
    787.         // Stop hovering over this object indefinitely.
    788.         //
    789.         // interactable - The hover-locked Interactable to stop hovering over indefinitely.
    790.         //-------------------------------------------------
    791.         public void HoverUnlock( Interactable interactable )
    792.         {
    793.             HandDebugLog( "HoverUnlock " + interactable );
    794.             if ( hoveringInteractable == interactable )
    795.             {
    796.                 hoverLocked = false;
    797.             }
    798.         }
    799.  
    800.         //-------------------------------------------------
    801.         // Was the standard interaction button just pressed? In VR, this is a trigger press. In 2D fallback, this is a mouse left-click.
    802.         //-------------------------------------------------
    803.         public bool GetStandardInteractionButtonDown()
    804.         {
    805.             if ( noSteamVRFallbackCamera )
    806.             {
    807.                 return Input.GetMouseButtonDown( 0 );
    808.             }
    809.             else if ( controller != null )
    810.             {
    811.                 //return controller.GetHairTriggerDown(); //Default grab controllers (With index Trigger)
    812.                 return controller.GetPressDown(SteamVR_Controller.ButtonMask.Grip); //Inplemented Grip Grab control.
    813.                 exjet.ForceBurst (); //Force Burst Method call;
    814.             }
    815.  
    816.             return false;
    817.         }
    818.  
    819.  
    820.         //-------------------------------------------------
    821.         // Was the standard interaction button just released? In VR, this is a trigger press. In 2D fallback, this is a mouse left-click.
    822.         //-------------------------------------------------
    823.         public bool GetStandardInteractionButtonUp()
    824.         {
    825.             if ( noSteamVRFallbackCamera )
    826.             {
    827.                 return Input.GetMouseButtonUp( 0 );
    828.             }
    829.             else if ( controller != null )
    830.             {
    831.                 //return controller.GetHairTriggerUp(); //Default grab controllers (With index Trigger)
    832.                 return controller.GetPressUp(SteamVR_Controller.ButtonMask.Grip);  //Inplemented Grip Grab control.
    833.                 exjet.ForceStop (); //Force Stop Method call;
    834.             }
    835.  
    836.             return false;
    837.         }
    838.  
    839.  
    840.         //-------------------------------------------------
    841.         // Is the standard interaction button being pressed? In VR, this is a trigger press. In 2D fallback, this is a mouse left-click.
    842.         //-------------------------------------------------
    843.         public bool GetStandardInteractionButton()
    844.         {
    845.             if ( noSteamVRFallbackCamera )
    846.             {
    847.                 return Input.GetMouseButton( 0 );
    848.             }
    849.             else if ( controller != null )
    850.             {
    851.                 //return controller.GetHairTrigger(); //Default grab controllers (With index Trigger)
    852.                 return controller.GetPress(SteamVR_Controller.ButtonMask.Grip); //Inplemented Grip Grab control.
    853.                 exjet.ForceBurst (); //Force Burst Method call;
    854.             }
    855.  
    856.             return false;
    857.         }
    858.  
    859.  
    860.         //-------------------------------------------------
    861.         private void InitController( int index )
    862.         {
    863.             if ( controller == null )
    864.             {
    865.                 controller = SteamVR_Controller.Input( index );
    866.  
    867.                 HandDebugLog( "Hand " + name + " connected with device index " + controller.index );
    868.  
    869.                 controllerObject = GameObject.Instantiate( controllerPrefab );
    870.                 controllerObject.SetActive( true );
    871.                 controllerObject.name = controllerPrefab.name + "_" + this.name;
    872.                 controllerObject.layer = gameObject.layer;
    873.                 controllerObject.tag = gameObject.tag;
    874.                 AttachObject( controllerObject );
    875.                 controller.TriggerHapticPulse( 800 );
    876.  
    877.                 // If the player's scale has been changed the object to attach will be the wrong size.
    878.                 // To fix this we change the object's scale back to its original, pre-attach scale.
    879.                 controllerObject.transform.localScale = controllerPrefab.transform.localScale;
    880.  
    881.                 this.BroadcastMessage( "OnHandInitialized", index, SendMessageOptions.DontRequireReceiver ); // let child objects know we've initialized
    882.             }
    883.         }
    884.     }
    885.  
    886. #if UNITY_EDITOR
    887.     //-------------------------------------------------------------------------
    888.     [UnityEditor.CustomEditor( typeof( Hand ) )]
    889.     public class HandEditor : UnityEditor.Editor
    890.     {
    891.         //-------------------------------------------------
    892.         // Custom Inspector GUI allows us to click from within the UI
    893.         //-------------------------------------------------
    894.         public override void OnInspectorGUI()
    895.         {
    896.             DrawDefaultInspector();
    897.  
    898.             Hand hand = (Hand)target;
    899.  
    900.             if ( hand.otherHand )
    901.             {
    902.                 if ( hand.otherHand.otherHand != hand )
    903.                 {
    904.                     UnityEditor.EditorGUILayout.HelpBox( "The otherHand of this Hand's otherHand is not this Hand.", UnityEditor.MessageType.Warning );
    905.                 }
    906.  
    907.                 if ( hand.startingHandType == Hand.HandType.Left && hand.otherHand.startingHandType != Hand.HandType.Right )
    908.                 {
    909.                     UnityEditor.EditorGUILayout.HelpBox( "This is a left Hand but otherHand is not a right Hand.", UnityEditor.MessageType.Warning );
    910.                 }
    911.  
    912.                 if ( hand.startingHandType == Hand.HandType.Right && hand.otherHand.startingHandType != Hand.HandType.Left )
    913.                 {
    914.                     UnityEditor.EditorGUILayout.HelpBox( "This is a right Hand but otherHand is not a left Hand.", UnityEditor.MessageType.Warning );
    915.                 }
    916.  
    917.                 if ( hand.startingHandType == Hand.HandType.Any && hand.otherHand.startingHandType != Hand.HandType.Any )
    918.                 {
    919.                     UnityEditor.EditorGUILayout.HelpBox( "This is an any-handed Hand but otherHand is not an any-handed Hand.", UnityEditor.MessageType.Warning );
    920.                 }
    921.             }
    922.         }
    923.     }
    924. #endif
    925. }
    926.  
    Thanks;
    Arthur
     
  2. CubicCBridger

    CubicCBridger

    Joined:
    Apr 19, 2017
    Posts:
    44
    just out of curiosity,

    Code (CSharp):
    1. hand.controller != null && controller.GetHairTriggerDown()
    you check controller on your hand reference isn't null but then go and call boolean method on separate controller reference (I'm not familiar with the steam vr api), does it automatically provide reference to controller? because it doesn't look like anywhere in your code you're assigning the controller reference.

    Code (CSharp):
    1. private SteamVR_Controller.Device controller;
    wouldn't it be better to get rid of it and use

    Code (CSharp):
    1. hand.controller != null && hand.controller.GetHairTriggerDown()