1
0

SteamVR_GazeTracker.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. using UnityEngine;
  3. using System.Collections;
  4. namespace Valve.VR.Extras
  5. {
  6. public class SteamVR_GazeTracker : MonoBehaviour
  7. {
  8. public bool isInGaze = false;
  9. public event GazeEventHandler GazeOn;
  10. public event GazeEventHandler GazeOff;
  11. public float gazeInCutoff = 0.15f;
  12. public float gazeOutCutoff = 0.4f;
  13. // Contains a HMD tracked object that we can use to find the user's gaze
  14. protected Transform hmdTrackedObject = null;
  15. public virtual void OnGazeOn(GazeEventArgs gazeEventArgs)
  16. {
  17. if (GazeOn != null)
  18. GazeOn(this, gazeEventArgs);
  19. }
  20. public virtual void OnGazeOff(GazeEventArgs gazeEventArgs)
  21. {
  22. if (GazeOff != null)
  23. GazeOff(this, gazeEventArgs);
  24. }
  25. protected virtual void Update()
  26. {
  27. // If we haven't set up hmdTrackedObject find what the user is looking at
  28. if (hmdTrackedObject == null)
  29. {
  30. SteamVR_TrackedObject[] trackedObjects = FindObjectsOfType<SteamVR_TrackedObject>();
  31. foreach (SteamVR_TrackedObject tracked in trackedObjects)
  32. {
  33. if (tracked.index == SteamVR_TrackedObject.EIndex.Hmd)
  34. {
  35. hmdTrackedObject = tracked.transform;
  36. break;
  37. }
  38. }
  39. }
  40. if (hmdTrackedObject)
  41. {
  42. Ray ray = new Ray(hmdTrackedObject.position, hmdTrackedObject.forward);
  43. Plane plane = new Plane(hmdTrackedObject.forward, transform.position);
  44. float enter = 0.0f;
  45. if (plane.Raycast(ray, out enter))
  46. {
  47. Vector3 intersect = hmdTrackedObject.position + hmdTrackedObject.forward * enter;
  48. float dist = Vector3.Distance(intersect, transform.position);
  49. //Debug.Log("Gaze dist = " + dist);
  50. if (dist < gazeInCutoff && !isInGaze)
  51. {
  52. isInGaze = true;
  53. GazeEventArgs gazeEventArgs;
  54. gazeEventArgs.distance = dist;
  55. OnGazeOn(gazeEventArgs);
  56. }
  57. else if (dist >= gazeOutCutoff && isInGaze)
  58. {
  59. isInGaze = false;
  60. GazeEventArgs gazeEventArgs;
  61. gazeEventArgs.distance = dist;
  62. OnGazeOff(gazeEventArgs);
  63. }
  64. }
  65. }
  66. }
  67. }
  68. public struct GazeEventArgs
  69. {
  70. public float distance;
  71. }
  72. public delegate void GazeEventHandler(object sender, GazeEventArgs gazeEventArgs);
  73. }