SteamVR_GazeTracker.cs 2.5 KB

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