programmerdude619 programmerdude619 - 9 days ago 6x
C# Question

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


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; < 0.5f){ x= Random.Range(xminBlue,xminRed); }else { x= Random.Range(xmaxRed,xmaxBlue); }
  5. Do the same as 4 to get the value of y

In this solution u dont need to reject any coordinate