Skip to main content
2 of 4
Clarify edge case (literally for edges)
izb
  • 870
  • 1
  • 8
  • 21

There is a slightly more brute-force method of doing this that does at least have the advantage of being pixel perfect and slightly more flexible. Please forgive the lack of pseudocode in what follows, but I think it should be fairly straight-forward to implement from a simple explanation.

The trick is in viewing the map not as a single staggered grid, but as two grids overlayed on top of one another. There's the odd-rows grid and the even-rows grid, but let's call them red and green instead so that we can create a pretty diagram...

Two grids, red and green

Notice on the right of that image I've marked a point with a purple dot. This is the example point we'll try to find in our original tile-space.

The thing to notice about any point in the world is that it will always lie in exactly two regions - a red one and a green one (Unless it's on an edge, but technically that makes that point slightly easier). Let's find those regions...

Two candidate regions

Now to pick which of the two regions is the correct one. There will always be exactly one answer.

From here we could do some more simple arithmetic and work out the squared distance from our sample point to each centre point of the two regions. Whichever is the closest will be our answer.

There is an alternative way however. For each test region, we sample a bitmap that matches the exact shape of our tiles. We sample it at a point translated into local coordinates for that single-tile. For our example it would look something like this:

Point samples

One the left we check the green region and get a hit (Black pixel). On the right we test the red region and get a miss (White pixel). The second test is of course redundant since it will always be exactly one or the other, never both.

We then arrive at the conclusion that we have a hit in the odd tile at 1,1. This coordinate should be simple to map to the original tile coordinates using a different transformation for odd and even rows.

This method also allows you to have simple per-pixel properties on the pixel test bitmap(s). E.g. white is off-tile, black is a hit, blue is water, red is solid.

izb
  • 870
  • 1
  • 8
  • 21