# Calculate a random position inside a 2D area excluding a subset

Given this area

- - - -
- X X -
- X X -
- - - -


I have a GameObject size 4x4 and inside another GameObject size 2x2.

I know how to calculate a random position inside the 4x4 zone (using GameObject position and collider size), but I do not know calculate a random position evading the 2x2 zone.

What I am using right now is:

1. Calculate position inside 4x4.
2. If that position is inside 2x2 go back to step 1.

But it is not a good way to do this. Do you know can I calculate a random position inside 4x4 area evading a 2x2 area?

I though generating small GameObjects, 1x1 instead if 4x4. So first select a random of the 4x4 tagged, for examble, as "IsWalkable", and then calculate a random position insided the selected small square.

• Your example suggests that your area is tile based; are you only dealing with integer coords or do you need a solution that supports decimal coords? – Pikalek Feb 20 '19 at 20:24

If your objects are always rectangular, a very simple way is the following:

• split the container object into N sub-rectangles that are fully accessible and M that are fully inaccessible. In your example N=8, M=1 except if the contained object is on a border (then N=5, M=1) or in a corner (N=3, M=1)
• compute the areas of each sub-rectangle: $$A_i ~~ \forall i \in \{1, ..., N\}$$
• draw the random index r in {1, 2, ..., N} with probability $$p(r = i) = \frac{A_i}{\sum_{i=1}^N A_i} ~~ \forall i \in \{1, ..., N\}$$

note that the sum in the denominator is just the area of the container minus the area of the contained rectangle.

• draw a random point inside the sub-rectangle r.

The approach works even if the container contains other rectangles. You can also adapt it for other shapes easily.

Here is a picture to get you started: if you can figure out the area of each of the labelled rectangle and if you can write a function that draws a point at random in a rectangle, you are done. :)

• It's not too important to care for N if it's always going to be one contained rectangle. Then always use N=8 and as result 3 or 5 sub-rectangles will have area zero when the contained is on a border or corner. However if you have several rectangles contained in the container, you will have to compute N – Alexis Feb 20 '19 at 14:43
• My maths are not the best. I need to "translate" it to my language :) I will try it. Vote up for the usefull response. – Jordi Huertas Feb 20 '19 at 17:10