Hi guys,
I am doing a Hololens app using Unity 3D engine now and I want to implement one specific function, which is when the user is looking a 3D game object (for example, like a cube), it could highlight (or simply change color) the face that the cursor is on.
I did some research and find for me it is not an easy question. One solution I can think of is to first know which mesh triangle the user is gazing by getting it’s index. And because every face has different triangle index so I could use some simple if else or case statement to determine which face the user is gazing. Then I would switch the color for all triangles in that face. When user changes the face he is gazing at, just set back to the original color.
Am I doing this right? Or there is better solution? It would be great if someone could give a code example with some comments.
Any advise or suggestion are welcome!
Thanks!
The code I have some far is like this, but it does not work:
public class FindTriangleIndex : MonoBehaviour {
GameObject cursor;
// Use this for initialization
void Start () {
cursor = GameObject.FindGameObjectWithTag(“cursor”);
if (cursor == null)
{
Debug.Log(“cursor not found”);
}
}
// Update is called once per frame
void Update () {
//This generates our ray. We input the positions x, and y, as screen height and width divided by two to send a ray towards whatever the
//screen center is viewing.
//Camera.main is a static var, capable of being accessed from any code without references.
Ray ray = Camera.main.ScreenPointToRay(cursor.transform.position);
//This defines a RaycastHit object. Its information is filled out if Physics.Raycasthit actually hits.
RaycastHit hit = new RaycastHit();
//This uses the ray’s parameters to call physics.raycast. Mathf.Infinity is the distance the raycast will go before giving up. [Don’t worry, distances of this size cause no lag].
//We specify ‘out’ as that is just how c# rolls. [It goes into variable references, ETC. All of this is automagic in JS]
Debug.Log(Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity));
if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity))
{
//This is the index of the tri the camera is looking at:
int ind = hit.triangleIndex;
Debug.Log("Hit tri index is " + ind * 3);
}
}