- Home /
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:
And here is a closer look to the secondary camera setup:
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:
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.
Answer by whydoidoit · Apr 20, 2013 at 08:12 PM
Convert the position of the sphere to the viewport in the orthogonal camera:
var point = orthCamera.WorldToViewportPoint(spherePosition);
http://docs.unity3d.com/Documentation/ScriptReference/Camera.WorldToViewportPoint.html
Create a ray to cast from the other camera:
var ray = perspCamera.ViewportPointToRay(point);
http://docs.unity3d.com/Documentation/ScriptReference/Camera.ViewportPointToRay.html
Your answer
![](https://koobas.hobune.stream/wayback/20220613100717im_/https://answers.unity.com/themes/thub/images/avi.jpg)