I’m creating a game in html5’s canvas just for educational purpose.
My maths skills are very bad. I can’t understand how to get the tile location x&y on the tileset and i don’t understand either why those informations are not directly stored in the tmx file.
Thank you in advance ! (i will feel stupid soon ,)
var tile_id = id - set.firstgid;
var set_width = set.imagewidth / set.tilewidth;
var tile_x = tile_id % set_width
var tile_y = Math.floor(tile_id / set_width);
ctx.drawImage(
set.img, tile_x * set.tilewidth, tile_y * set.tileheight,
set.tilewidth, set.tileheight,
x * set.tilewidth, y * set.tileheight,
set.tilewidth, set.tileheight
);
This code does not take into account tile margin and tile spacing, which also affect where the tile rectangle of a given tile is on the tileset.
It’s simply because that information would be redundant since it can be derived from the existing information. You can avoid calculating it each time when drawing the tile by producing this data while or directly after loading the map.