Place (Scatter) random rectangles in a bigger rectangle

122 Views Asked by At

I am making a voxel game and creating the terrain, The ground and elements on it are rectangles,

First of all I want to generate the elements guaranteed that their total area is less than ground space.

in one dimensional space I figured ways to do so but couldn't apply any of them on 2d, on of them is get the sum of remaining length and place elements with some spacing while my left space is decreasing.

I tried another way by dividing the ground rect to smaller rects but it doesn't fit my needs.

1

There are 1 best solutions below

3
On

One possible way,

  1. Generate four numbers between 0 and 1 (say $x_1,x_2,y_1,y_2$) such that $x_1<x_2$ and $y_1<y_2$.
  2. Make a rectangle such that the two corners are $(x_1,y_1)$ and $(x_2,y_2)$.
  3. Now draw verticle and horizontal lines by extending the edges of the rectangle such that a tic-tac-toe kind of a figure is generated.
  4. You have now 9 rectangles so that you can now recurse on your problem.
  5. If any time you feel like your rectangle is of apt size, just choose the entire rectangle.

This way you can generate rectangles that don't overlap and the sum of areas is less than the total area.

If you want the rectangles to be at different angles, then a similar approach can be used. Just the difference is that you will have to generate an extra number specifying the angle of the edge.