Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

spawning random objects in the camera view

Discussion in 'Editor & General Support' started by raghadalghonaim, Aug 11, 2020.

  1. raghadalghonaim

    raghadalghonaim

    Joined:
    Apr 22, 2020
    Posts:
    54
    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)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,697
    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.
     
  3. raghadalghonaim

    raghadalghonaim

    Joined:
    Apr 22, 2020
    Posts:
    54
    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... :(
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,697
    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.
     
  5. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,464
    Code (CSharp):
    1. public static Vector3 ScreenPositionIntoWorld(Vector2 screenPosition, float distance)
    2. {
    3.   Ray ray = Camera.main.ScreenPointToRay(screenPosition);
    4.   return (ray.direction.normalized * distance);
    5. }
    Usage:
    Code (CSharp):
    1. Vector3 worldPosition = ScreenPositionIntoWorld(
    2.   // example screen center:
    3.   new Vector2(Screen.width / 2, Screen.height / 2),
    4.   // distance into the world from the screen:
    5.   10.0f
    6. );
     
    PraetorBlue likes this.