Calculate distance HoloLens to object and object to object

This guide consists of two scenes. In the first scene, you will calculate the distance between the HoloLens and any surface in the real world. In the second scene, you will perform calculations that summarize distances from multiple three-dimensional points.

calculationdistance.png

The calculation of the distance between the HoloLens and any three-dimensional point in space is explained through the following method. To recognize surfaces in the real-world environment, you can utilize the spatial mapping component from HoloToolkit. These two points represent the location of the HoloLens and the position recognized by the HoloLens as a surface through gaze.

GlobalCursor.cs

void Update()
    {
        var headPosition = Camera.main.transform.position;
        var gazeDirection = Camera.main.transform.forward;
        
        var gazePosition = GameObject.Find("GlobalCursor").transform.position;

        RaycastHit hitInfo;

        if (Physics.Raycast(headPosition, gazeDirection, out hitInfo))
        {
            meshRenderer.enabled = true;

            this.transform.position = hitInfo.point;
            
            this.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);

            //Display distance (Hololens - Cursor)
            float distance = Vector3.Distance(headPosition, gazePosition);
            TextMessage.Instance.ChangeTextMessage(string.Format("Distance: {0}", distance >= 1.0f ? distance.ToString("####0.0") + "m" : distance.ToString("0.00") + "cm" ));
        }
        else
        {
            meshRenderer.enabled = false;
            TextMessage.Instance.ChangeTextMessage(string.Empty);
        }
    }
}


You can access and download this sample from GitHub using the following link: https://github.com/gntakakis/Hololens-DistanceCalculations-Unity.

Leave a comment