x


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 -

alt text

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).

more ▼

asked Mar 29 '10 at 12:56 AM

dhendrix gravatar image

dhendrix
2.2k 25 34 59

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Mar 29 '10 at 04:29 AM

Murcho gravatar image

Murcho
2.7k 12 23 53

Was not aware of that function, thanks for the info!

Mar 29 '10 at 05:22 AM dhendrix
(comments are locked)
10|3000 characters needed characters left

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!

more ▼

answered Mar 29 '10 at 01:20 AM

e.bonneville gravatar image

e.bonneville
5.7k 100 116 165

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.

Mar 29 '10 at 01:51 AM dhendrix

Ah, you're doing zooming... I was worried about that. Try putting them all in a single GameObject, then scaling that in proportion to the cameras field of view.

Mar 29 '10 at 02:10 AM e.bonneville
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1528
x885
x152

asked: Mar 29 '10 at 12:56 AM

Seen: 1787 times

Last Updated: Mar 29 '10 at 12:56 AM