Search code examples
mathdrawingtilesisometric

Given I know an isometric diamond map coordinate, how do I figure out which tile was clicked?


My tile engine is coming along. It can draw square, hexagonal and isometric staggered viewpoints. Where I'm struggling is with the isometric rotated (or diamond) viewpoint. Below is a picture of a 10x10 diamond map and the (simplified) code used to draw it. The tiles are 128x64.

http://garrypettet.com/images/forum_images/5%20col%20x%205%20rows.png

for row = 0 to rowLimit

  for column = 0 to columnLimit

    x = column * (TileWidth/2) + (row * (TileWidth/2)) + Origin.X
    y = (column * (TileHeight/2)) - (row * (TileHeight/2)) + Origin.Y

    // Draw the tile's image
    buffer.Graphics.DrawPicture(Tiles(column, row).Image, x, y)

  next column

next row

// Draw the buffer to the canvas
g.DrawPicture(buffer, 0, 0)

I know that this will draw the contents of the whole of Tiles() and not just those visible on screen but I'm trying to get the basics first.

What I can't figure out is an easy way to convert x,y coordinates on the map to tile column,row coordinates. I tried to reverse:

x = column * (TileWidth/2) + (row * (TileWidth/2)) + Origin.X
y = (column * (TileHeight/2)) - (row * (TileHeight/2)) + Origin.Y

To work out column and row given x and y and came up with this:

column = ((x/2) - (Origin.X/2) + y + Origin.Y) / TileHeight
row = ((x/2) - (Origin.X/2) - y - Origin.Y) / TileHeight

But that doesn't seem to work. Can anyone think of a better way to do this? Is there a better way to transform a grid of rectangles into a diamond and back again (given that I know very little about matrices....).

Thanks,


Solution

  • I am not sure I can follow the details of your problem, but if you are just looking to solve your formulas for x and y in terms of column and row, then

    column=(x + y - (Origin.X + Origin.Y))/TileWidth
    row = (x - y - (Origin.X - Origin.Y))/TileHeight
    

    The easiest way to get these expression is to first add the expressions for x and y and solve for column, then subtract them and solve for row.