spawning random objects in the camera view

I want to spawn random 3D models within the camera view, I have a target object at position [0,0,0] and I want to have [0,10] random objects around the target.

My problem is that the camera is moving and rotating during the run time, so the view would change. How can I specify the range of values for the random object positions? is there a way to force it to find a place within the camera view?

Thanks in advance

P.S I’m not using colliders, I check collisions by myself (by finding the distance between the objects)

Well you could pick a random pixel on the screen and then get the corresponding world location by projecting that pixel out into the game world from the camera’s viewport.

Yes, that’s sound to be it. But I’m not exactly sure how to do it. I want to get the center of the camera to be my reference point, and spawn object right and left, forward and inward.

I tried using Camera.ScreenToWorldPoint with no luck… :frowning:

Camera.ScreenToWorldPoint is a good start. That will give you a point on the camera’s viewport, which will be very close to the camera. You’ll want to try to project that point out into the world to a certain distance. What that distance is really depends on how your game is laid out and where exactly you want the objects to spawn.

public static Vector3 ScreenPositionIntoWorld(Vector2 screenPosition, float distance)
{
  Ray ray = Camera.main.ScreenPointToRay(screenPosition);
  return (ray.direction.normalized * distance);
}

Usage:

Vector3 worldPosition = ScreenPositionIntoWorld(
  // example screen center:
  new Vector2(Screen.width / 2, Screen.height / 2),
  // distance into the world from the screen:
  10.0f
);
1 Like