c++tiling

How can I efficiently store a grid of rectangles?


So I was thinking about making a building game with different shaped rectangles instead of just squares, but I can't figure out an efficient way to do this. For example, I don't want to have a grid of tiles like tetris that make up each shape. I want each piece to be one object with a width and height. For example a 2*3 piece wouldn't take up 6 tiles, it would just be a single rectangle. I have to be able to do organize the pieces efficiently and be able to get the piece at a certain coordinate. If I just used a two dimensional array of tiles it would use memory that I don't need.


Solution

  • To get the rectangle at any given coordinate is very expensive on resources no matter how you do it, but probably the most efficient way would be to create a loose grid that the rectangles are not confined to. Whenever a piece moves it will update a two-dimensional array with its reference in all the squares it either fully or partially contains. Whenever given a coordinate, calculate which square in the grid the coordinate is in and then from that you can do more extensive calculations to check if the coordinate is actually inside the rectangle or not.