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