Getting a top-left position of a tile inside a til

2019-08-12 07:15发布

问题:

I have a tileset(a image full of other small images). And I wanna get one of those little images called tile so I can do something with it. I know the size of each tile(they're all the same size). I have two equations:

x = (i % tiles_hor) * tile_h
y = (i % tiles_ver) * tile_w

x = (i % tiles_hor) * tile_w
y =  (i / tiles_hor) * tile_w

where i means the index of the tile i wanna get;
tiles_hor is the number of tiles horizontally;
tiles_ver is the number of tiles vertically;
tile_w and tile_h is the width and height of each tile inside the tileset, respectively;

The tiles receive their index sequentially, like this:

01 02 03 04 05 
06 07 08 09 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

So each pair of digit it's the index of a tile inside the tileset. Let's say I wanna get the tile 04(assuming the tiles have a 32x32 size each): with the first equation:

x = (4 % 5) * 32 = 128. So it's x position inside the image is 128
y = (4 % 5) * 32 = 0. So it's y inside the image is 0;

with the second equation:
x = (4 % 5) * 32 = 128. So it's x position inside the image is 128
y = (4 / 5) * 32 = 0. Here's is 0, cause we're first rounding the first expression for the closest minor number(i don't know if my expression is right. Please correct me if it's not).

Note that we're considering a perfect square tileset (in this case 5x5)

My question is:
The second works for most cases. The first stop working when there's no perfect squares tileset's and with a high height. So what am I doing wrong there?

Also, how can be a equation that is letting out a really important value (tiles_ver and tile_h) can be right? What am I missing there?

回答1:

x = ((i - 1) % tiles_hor) * tile_w
y = ((i - 1) / tiles_hor) * tile_h