- Home /
Raycasting with multiple cameras and displays
I'm new to Unity but know C# pretty well, I'm trying to build a demo with 4 cameras and 4 displays. Each display has it's own camera, and the cameras viewports don't overlap. I need to check if the user has clicked on items on each display, I'm using raycasting for this specifying the camera. The problem is that Input.mouseposition
returns the same coords no matter which display is clicked, so items in the same position on each display register the click
e.g. display 1 has an item at x 10 y 10 and display 2 also has an item at x 10 y 10, when the user clicks on the item on display 1 the item on display 2 also thinks it's been clicked.
private static GameObject HitTest(Camera cam)
{
if (Input.GetMouseButtonDown(0) && cam != null)
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100))
{
Debug.DrawRay(ray.origin, ray.direction * 500, Color.green, 60);
// The gameobject hit
GameObject hitGameObject = hit.collider.gameObject;
Logger.instance.LogMessage("hit " + hitGameObject.name);
return hitGameObject;
}
}
return null;
}
Does anyone know a way round this without relying on checking the display the mouse is currently on, as this won't work when testing in unity as everything is then on one display. Thanks for any help.
Answer by xxmariofer · Jan 17, 2019 at 11:07 AM
Have you tried using rather than ScreenPointToRay ViewportPointToRay? i have not used it but checking unity documentarion feels like it should work, if not maybe layering objects depending the Viewport is another option.
yes, when working with multiple viewports, you need to look deeper into the difference between ScreenPoint and ViewportPoint families of functions.
Thanks for the replies, this looks like the way to go. But I can't get which viewport is clicked, as Input.mousePosition is the same if you clicked on the same point on either display.
Your answer
Follow this Question
Related Questions
How do I get my camera to rotate around the y=0 coordinate it's looking at? 0 Answers
Security Camera Scripts? 1 Answer
Displaying multiple GUITextures On One Camera 0 Answers
Render Texture display different with its camera preview 1 Answer
Camera only displaying one object even though culling mask is set to everything 1 Answer