- Home /
Getting position where raycast goes offscreen
Is it possible to fire a raycast in a direction, then get the position when the raycast hit the edge of the screen in world coordinates? For example -
Let's say this is a 2d game and the black circle is the player. He fires off raycasts in arbitrary directions (the blue rays). Can we get the position where the ray left the camera viewport? Apologies if I'm missing something simple here(which is likely).
Answer by Murcho · Mar 29, 2010 at 04:29 AM
You can get the Camera Frustum planes by using the GeometryUtility.CalculateFrustumPlanes() function built into Unity. This function returns an Array of planes that make up the viewport. You can then use the algorithms on this page to determine where the intersection happened.
This should be faster to calculate than using colliders, and doesn't need to involve the physics engine at all.
Answer by e-bonneville · Mar 29, 2010 at 01:20 AM
I'm not exactly sure what you're asking. However, it seems to me that you want to find the position that the players bullet left the area you can view. One way to accomplish this is to create four box colliders. Arrange them around the edges of the screen and make them children of the camera. Then, using Raycast.Hit, you can find the positions at which they 'left the screen'. In other words, where they hit the colliders arranged around the edges of the screen. You can then use hit.point like this:
var hit : RaycastHit; var edgeOfScreenHit;
function Update () { if (Physics.Raycast (ray, hit)) { edgeOfScreenHit = hit.point;
} }
Hope this helps!
Well yes, you got the point of my question. I was throwing around the idea of doing colliders as you suggest, problem is it seems like a pain scaling them when the camera zooms in and out.
Ah, you're doing zoo$$anonymous$$g... I was worried about that. Try putting them all in a single GameObject, then scaling that in proportion to the cameras field of view.
Your answer
![](https://koobas.hobune.stream/wayback/20220612133556im_/https://answers.unity.com/themes/thub/images/avi.jpg)