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.
Asked
Active
Viewed 2,966 times
1
-
1Find a position in B and if it is also in A, try again (i.e. rejection sampling). – Nico Schertler Oct 14 '16 at 02:24
1 Answers
2
One Solution is same as Nico Schertler has mentioned in the comment
- Get the coordinate of each vertices of both the rectangle.
- 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)
- Do the same for Y coordinate and get (yminBlue,yminRed) . (ymaxRed,ymaxBlue)
- 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;
} - Do the same as 4 to get the value of y
In this solution u dont need to reject any coordinate

sagar
- 180
- 1
- 9
-
Thanks a lot for this solution, its just what I needed and very straightforward to understand. – programmerdude619 Oct 14 '16 at 04:43
-
I tested it and it works fine, just one question, why the < 0.5f? – programmerdude619 Oct 14 '16 at 05:25
-
sorry do not use random.value < 0.5f instead use the above code i have edited .this will help you to get value with equal probability any were in the blue region – sagar Oct 14 '16 at 06:30
-
and for the y axis, the if statement should be like if (Rand – programmerdude619 Oct 14 '16 at 08:04
-
1and for the y axis, the if statement should be like if (Random.value < GetRatio(yMinRed - yMinBlue, yMaxBlue - yMaxRed))? – programmerdude619 Oct 14 '16 at 08:06