2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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? \$\endgroup\$
    – Pikalek
    Feb 20, 2019 at 20:24

1 Answer 1

2
\$\begingroup\$

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. :)

illustration with 8 rectangles

\$\endgroup\$
2
  • \$\begingroup\$ 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 \$\endgroup\$
    – Alexis
    Feb 20, 2019 at 14:43
  • 1
    \$\begingroup\$ My maths are not the best. I need to "translate" it to my language :) I will try it. Vote up for the usefull response. \$\endgroup\$ Feb 20, 2019 at 17:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .