Tile coordinates on tileset

Hi there,

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 :wink:,)

Hello,

I somewhen wrote a small renderer for html5 / javascript. This was only a test… But it might help you understanding how to translate the ids to x/y coordinates: https://gist.github.com/Ablu/0614a5967e17ed0b4380#file-index-htm-L62

The relevant snippet:

  var x = cell % map.layers[layer].width;
  var y = Math.floor((cell - x) / map.layers[layer].height);

cell is the index of the map cell in the layer array.

Regards,
Ablu

Since @DrimZ was asking about the coordinates of the tile, I believe the relevant snippet is rather https://gist.github.com/Ablu/0614a5967e17ed0b4380#file-index-htm-L44-L54

      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.