Finding tileX and tileY based on x and y (and vice versa) in isometric 2D view
Posted by: ekharrtoll on 08/21/2015 | Add Revision
I'm working on 2d Isometric game in ruby and gosu, although my problem is probably universal. My map is saved in 2d array:
@map_tiles[layer][y][x] = tile_id
Each tile is displayed on coordinates:
isoX = (x * @tile_width/2) - (y * @tile_height) isoY = ((x * @tile_width/2) + (y * @tile_height)) / 2
So it's displayed in "diamond" like way. But I'm having a problem with calculating two things. - Entity's tile_x and tile_y (on which tile is the entity positioned) when given x and y, and; - Entity's x and y when I'm sending it's tile_x and tile_y.
One method is pretty much the other one reversed. I tried various methods I found over internet, but either I'm doing something wrong, or I don't understand the instructions correctly. The closest I got is:
@x = (tile_x * 32) - (tile_y*32) @y = ((tile_x * 32) + (tile_y * 32) / 2)
for finding @x and @y based on tiles (player "teleportation" method), and
@tile_x = ((@x / 32) + (@y / 32)) / 2 @tile_y = ((@y / 16) - (@x / 32)) / 2
But they kinda don't work correctly.
- When I send player to tile position (4, 3), he is displayed at (5, 4), and after recalculating it's tile_x/y position, printing says it is at tiles (3,5)
- When I send player to tile position (3, 4), he is displayed at (4, 5), and after recalculating it's tile_x/y position, printing says it is at tiles (2,5)
- When I send player to tile position (4, 2), he is displayed at (5, 3), and after recalculating it's tile_x/y position, printing says it is at tiles (2,5)
So you can clearly see that something's not right here.
That's pretty much it, thanks in advance. I can post the code on github if it's neccessary, but I reckon the problem lies in what I posted.