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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

help ! how to generate object with specific area

Discussion in '2D' started by andy30929, Apr 10, 2020.

  1. andy30929

    andy30929

    Joined:
    Feb 26, 2018
    Posts:
    17
    I want to generate object nearby the player, but not out of bound for the game
    some code below

    Code (CSharp):
    1.     void zombiegenerate()
    2.     {
    3.  
    4.         pos = Random.insideUnitCircle * 10;
    5.         pos = player.position + pos.normalized * ( 10 + pos.magnitude);
    6.         Instantiate(zombie, pos, Quaternion.identity);
    7.        
    8.     }
    i can generate the zombie nearby the player now, but when the player walk near to the bound, it will generate enemy outside the game, how can i avoid this ? any suggestion
     
  2. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,323
    If you know the dimensions of the world (e.g. a Bounds) or could "new Bounds()" it into existence, you could use myBounds.ClosestPoint(somePosition) to get a position that is confined to the edges of your world.

    To further refine that, it might look funny if enemies are generating right on the edges of the world. So you might generate bounds that are somewhat smaller than the true size of your world.
     
    eses likes this.
  3. andy30929

    andy30929

    Joined:
    Feb 26, 2018
    Posts:
    17
    bound may a bit complex for me (idk how to use it), i just simple solved by compare x y value to re spawn the object.
     
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @andy30929

    It won't get much easier than using bounds like @Lo-renzo said, actually it probably is easier than manually calculating x and y positions... check the docs.

    If you were using navigation mesh, then you could just get the closest point on navmesh... but you didn't say, how you have setup your enemy movement.