Raycast from one camera using a gameobject relative to another camera

Hellow Unity community,

I’ve been trying to solve this problem for a while now but nothing I’ve been trying seems to work. Here is the setup:

  • I have a main perspective camera that points to the scene in a fixed position
  • I have a secondary orthographic camera far away that only contains a spehere in its view

Here is a screenshot of the setup:
Scene setup

And here is a closer look to the secondary camera setup:
Secondary camera

As you can see from the first image, combined, I see the yellow sphere in my main camera. That yellow sphere can only move up/down/left/right by an XBOX controller. The secondary camera and the yellow sphere are under the same parent, so at 0,0,0 local position, the yellow sphere is dead center in front of the secondary camera. The secondaty camera has a local position of 0,0,-2.

What I’m trying to figure out is how to ray cast from the main camera towards the yellow sphere and get what it hit.

For example, in this screenshot, I’d like to cast a ray from and get a hit on the brown cube the yellow sphere is over:
Example

Any ideas on how to do this? Is there a better way to set this up? Basically, I’m trying to simulate a mouse cursor that moves on the X/Y axis relative to the camera using an XBOX controller.

Thanks in advance.

1 Answer

1

Convert the position of the sphere to the viewport in the orthogonal camera:

  var point = orthCamera.WorldToViewportPoint(spherePosition);

Create a ray to cast from the other camera:

 var ray = perspCamera.ViewportPointToRay(point);

Works like a charm! Thank you very much!