1
votes

I'm trying to convert a mouse event into a VR Raycast event.

I've Input.mousePosition.x & Input.mousePosition.y as the coordinate of a mouse click event. I want to apply the same event on a VR Raycast hit.

I've the following code

Ray ray = new Ray(CameraRay.transform.position, CameraRay.transform.forward);
RaycastHit hit;

if (GetComponent<Collider>().Raycast(ray, out hit, 100)) {
     Debug.Log ("True");
    Vector3 point = camera.WorldToScreenPoint(hit.point);
} else {
    Debug.Log ("False");
}

From the Raycast hit point, how do I get the equivalent x-y coordinates of where the Ray hits the collider?

Update:

The following script is attached to a color picker object in my Unity setup for Google Cardboard. On hover on the color picker, I want to get the coordinates of where the Raycast hits the collider (so that I can get the color in that coordinate).

enter image description here

Question 1: On the FixedUpdate, I've an if statement if (GetComponent<Collider>().Raycast(ray, out hit, 100)) and it's returning false. What am I missing here?

Question 2: Am I correct to assume that if the hit.point is set, I could get the x,y,z coordinates of the point where the ray hits the collider to be point[0], point1 and point[2]?

1

1 Answers

1
votes

I'm not a huge expert on VR in Unity, but you would usually use Camera.WorldToScreenPoint for these purposes. To use it on the main camera, use these lines:

Ray ray = new Ray(CameraRay.transform.position, CameraRay.transform.forward);
RaycastHit hit;

if (GetComponent<Collider>().Raycast(ray, out hit, 100)) {
    Vector3 point = camera.WorldToScreenPoint(hit.point);
}

The z value gives you the distance from the camera, in case you were interested in that. The Unity documentation: https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

EDIT:

Question 1:

RaycastHit hit;

if (Physics.Raycast(CameraRay.transform.position, Vector3.forward, out hit)) {
     Debug.Log ("True");
    Vector3 point = camera.WorldToScreenPoint(hit.point);
} else {
    Debug.Log ("False");
}

Attempt using this code instead, from what I've read, Physics.Raycast() is almost always better to use than Collider.Raycast().

Question 2:

Vector3[] point = new Vector3[3] {hit.point.x, hit.point.y, hit.point.z};

This creates an array named point that has the three variables assigned, although the z coordinate can be discarded for use on a 2D color wheel.