cbros2008
cbros2008

Reputation: 353

Calculating the area and position of dynamically formed rectangles

Hello stackoverflow community,

I'm working on a puzzle game using Cocos2D/Box2D were the player draws lines on the screen. Depending on were the player draws, I want to then work out the area and position of the rectangles that appear as a result of the drawn lines.

I've currently got an array of all lines in the game so I know their (x, y) positions and sizes but I'm at a lost as to how to calculate the area and Cartesian coordinates of the rectangles that are dynamically formed. To help illustrate the problem, please see the following:

Blue rectangles

In the image above, you can see a black border. Contained within this are 4 grey lines which have been drawn by the player. From this, 5 blue rectangles have been formed. Any guidance or advice on how I can calculate the area and Cartesian coordinates of the rectangles would be a great help.

Upvotes: 1

Views: 256

Answers (1)

user1118321
user1118321

Reputation: 26395

I wonder if it would be easier to convert the lines into a set of rectangles?

Start with a list of rectangles which only contains the main big rectangle. For each line, see which rectangle in the list contains it. Remove that rectangle from the list of rectangles and replace it with 2 smaller rectangles defined by the line.

Once you have the list of rectangles, you can easily calculate their area by just doing (width * height).

Upvotes: 2

Related Questions