Working with regions

Hi folks,

I’m curious about defining regions using objects. For example, if you draw a rectangular object, is there a way to check via coding where that rectangular region is? Or, if it was circular, or whatever shape.

Really, I would like to know which tile locations are encompassed by the defined region. Then I would like to iterate over those tiles and do something with them in code.

– or is the only alternative to make rectangular objects the same size as the tiles and copy/paste them over the region I want to define and then iterate over those objects.

(I’m using pytmx under this)

Any thoughts?

Of course there is, though that’s a question unrelated to Tiled xP You need to check if the theoretical polygon representing your tile intersects the object.

For axis-aligned rectangles, this is trivial, you just need to check whether any of the tile’s four corners are between the four corners of the region. For circles, it’s also trivial, you just need to check whether the distance between their centre points is less than the sum of their radii (which will be width/2). For other shapes, like ellipses and non-rectangular polygons, it’s more complicated, and you should look up polygon or shape intersection algorithms or libraries.

PyTMX loads the objects the same way they’re represented in the TMX file - just the width, height, rotation angle, and possibly a shape (e.g. “ellipse” or a collection of points representing a polygon). These data are sufficient to represent the shapes, but you may need to do some work on them to make doing maths on them easier. Find a library or formulae you like, then worry about converting the data to a format that suits them.
FWIW in my games, I only use axis-aligned rectangles for regions because they’re the easiest to deal with, and not having to account for rotation and other shapes saves me a lot of headaches.

If both the regions and the tiles/objects you’re checking within them are static, then you may want to do all of this at load time, and keep static lists of the tiles and the region(s) they belong to, for easier access. This will be much more efficient than doing intersection checks every frame. You could even build the regions into your underlying physics representation, perhaps.
If any of the interacting objects are dynamic, then you will have to do this every frame, but you could potentially get away with only checking relevant tiles (e.g. tiles surrounding dynamic entities like the player).

1 Like