Search code examples
c#unity-game-enginevectorspawning

Unity, get random position within an area?


as the image below shows, I would like to find a random position within the blue area (B) and not the red area (A). How can I achieve this? A and B are currently 2 colliders. I just need a position within B but it cant be within A. Thanks in advance.

A and B areas


Solution

  • One Solution is same as Nico Schertler has mentioned in the comment

    1. Get the coordinate of each vertices of both the rectangle.
    2. take the x coordinate of min x of blue triangle and min coordinate of red triangle as a pair.(xminBlue,xminRed). Take the x coordinate of max x of red triangle and max coordinate of blue triangle as a pair.(xmaxRed,xmaxBlue)
    3. Do the same for Y coordinate and get (yminBlue,yminRed) . (ymaxRed,ymaxBlue)
    4. Use if(Random.value < GetRatio(xminBlue-xminRed),xmaxRed-xmaxBlue){ x= Random.Range(xminBlue,xminRed); }else { x= Random.Range(xmaxRed,xmaxBlue); } float GetRatio (float distance_1,float distance_2){ return distance_1 / distance_1 + distance_2;
      }
      enter image description here
    5. Do the same as 4 to get the value of y

    In this solution u dont need to reject any coordinate