Hey guys, here is a quick C# script for Unity Game engine and Oculus Rift which enables you to do quick gaze detection tests and use it as a input.
In this example you have a bunch of cubes and when you look at any of them, a small text will appear above the cube which you are looking at.
To use this script you need to first create a sample scene as shown above with cubes and attached with child text objects and use the below script in a empty game object, in this example the script is added to “GazeDetector”.
using UnityEngine; using System.Collections; public class gaze_highlighter : MonoBehaviour { public OVRCameraRig cameraController = null; public GameObject[] MySampleCubes; void Awake() { if (cameraController == null) { Debug.LogError ("ERROR: Missing camera controller reference on " + name); enabled = false; return; } // Initially let us disable rendering of text on all the cubes. for (int i = 0; i < MySampleCubes.Length; i++) { Renderer[] r = MySampleCubes[i].GetComponentsInChildren<Renderer>(); r[1].enabled = false ; } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { // handle user gaze Ray ray = new Ray(cameraController.centerEyeAnchor.position, cameraController.centerEyeAnchor.forward); RaycastHit hit = new RaycastHit(); // Check if the ray is hitting the colliders in everty frame for (int i = 0; i < MySampleCubes.Length; i++) { // If ray hits the collider then enable rendering of text if(MySampleCubes[i].GetComponent<Collider>().Raycast (ray, out hit, 100.0f)){ Renderer[] r = MySampleCubes[i].GetComponentsInChildren<Renderer>(); r[1].enabled = true ; } // If ray does not hit the collider the ndisable rendering of text. else { Renderer[] r = MySampleCubes[i].GetComponentsInChildren<Renderer>(); r[1].enabled = false ; } } } }
The above script is basically taking your Oculus camera controller and generating a ray according to the viewing direction during every frame. Then we check if the ray collided with any of the cubes, if our ray collided then we access the child of our cube and enable its text rendering , similarly if our ray is not colliding with a cube, we just disable the rendering of the cubes child. Simple !