How would i calculate the size of a 2D area closed off by multiple colliders?

Problem: How can i calculate the size of the closed off areas as shown below?

Context:
I am currently creating a physics-based Tetris-like game, where the objective is to create big, closed off, empty spaces. When the player has completed the level by letting the blocks reach the top of the screen, the game is supposed to give a score based on the size of the closed off empty areas on screen.


All i need is a few pointers. Maybe a bit of pseudocode or a few tips about some useful methods. Any good (and bad) ideas are welcome!

Currently I’m thinking about ways to use the contact points between the Rigidbody2D’s, but i find it difficult to calculate the area of these weird shapes from the coordinates of their corners coordinates alone (and to find the correct shapes in the first place).

Thank you in advance :slight_smile:


Edit: I could just fill the game area with thousands of nodes, and then whether each of them is obscured by a block, but i feel like this is an extremely inelegant way to do this, as it is pretty inaccurate and creates a lot of game objects at once.


(Also, i don’t know if this sort of question belongs here…)

Well, there’s no trivial solution to this. Generally i see two possible solutions:

  • analytical approach
  • method of exhaustion (sort of).

Going the analytical route is extremely difficult since you have to collect all collision points and actually determine the border of each area. Due to inacuracies there might be gaps you wouldn’t consider gaps.

The simpler yet a bit more expensive and not as precise approach could be to create a texture of the size of your game area. Now you would draw in the border of your game pieces with lines. Note that you might want to expand the border of each piece by a small amount to ensure touching pieces create overlapping line segments.

Now you can fill your pieces with a certain color. You can use my FloodFill though a more optimised version might be useful. Finally just search through the image and look for unchanged (white?) pixels and use floodfill again with a different color. As you fill an area you may want to count the number of pixels filled for each area. To rule out the top area you probably want to start filling with the top row and ignore any areas that were filled from those starting points.

Since you have to do a lot of drawing / filling it would be recommended to directly use a Color array and create a modified version of the line drawing and filling methods.

http://wiki.unity3d.com/index.php?title=TextureFloodFill