instantiate prefab directly off camera

sorry for the kinda-sorta-possibly repetitive question but im just not wrapping my head around how to start an object off camera while being precise (as in not just Vector3(0,-5000,0))

my objects will be created randomly across the x axis but at y=0 and z=0 and my camera is at 0,0,-25, so im trying to figure out a. where to position them directly below the camera’s view so when i add vertical velocity to them they will appear on screen, and b. why the Camera.ScreenToWhateverPoint functions dont seem to be giving me what i want (i tried passing in a vector of zero and a vector where x is Screen.width to get world coords of the left and right edges of the screen but that didnt seem to work at all, returned something like (.25, 10,40) and (1.25, 10, 40)).

if it helps u visualize the problem, think Fruit Ninja - spawning objects below screen and shooting them into view and allowing gravity to do the rest

1 Answer

1

The way I do this is to use Viewport coordinates. Viewport coordinates start in the bottom left of the screen at (0,0) and go to the top right of the screen at (1,1), so anything out of this range is off the screen. This calculation is for a single position, so you have to give a bit extra to accommodate the size of the object. For example (-0.1, .5) would be off the left side and at the middle of the screen on the ‘Y’ value. To make the conversion, you have to know how far in front of the camera you want to generate the point. So let’s say it is 10 units in front. You can do it like:

Vector3 v3Pos = new Vector3(-0.15f, .5f, 10);
v3Pos = Camera.main.ViewportToWroldPoint(v3Pos);

ah, very cool thanks. the piece i was missing is that viewport was bottom left and was normalized. does the z coord here matter much really, if my camera is at -25 and everything is at 0, i should set it to Vector3(0, -1, 25) then?

The Z is the distance in front of the camera, so setting it to 25 should work just fine.

great, seems to work great, but one last question - the prefabs that i want off screen, right now when i use a vector of (0, -.5, 25) its like WAY off screen, how can i go about figuring out the absolute bare minimum? ie in flash id do screenHeight + prefab.height for my calculation so that it was just offscreen