Jerkoco Jerkoco - 1 year ago 63
Javascript Question

get X and Y of a tile on a tileset

I'm trying to write a function that returns the position of a tile on a tileset.

I wrote some code for that but that seems unnecessarily complicated.

how each tile has a number

// My old code:

function getXPosByNumber(width, height, tilesize, tilenumber) {
if ((tilenumber % (width / tilesize) - 1) < 0) {
return width - tilesize;
} else {
return (tilenumber % (width / tilesize) - 1) * tilesize;

function getYPosByNumber(width, height, tilesize, tilenumber) {
return (Math.ceil(tilenumber / (width / tilesize)) - 1) * tilesize;

How can I access any tile coordonates with a cleaner/simpler code ?


Answer Source

Here's what I figured out to simplify. I found that height isn't so relevant to calculate either X or Y. The important factor here is how much it spreads horizontally.

Then, since a specific tileset will more likely always have the same width and tilesize, I suggest a more "Object"-ified approach so you don't have to constantly remember its configuration. Personally, I like to wrap constants and configurations so I can write lightweight code afterwards:

var tileset = function(width, tilesize) {
    this.width = width;
    this.tilesize = tilesize;

// calculate X by tilenumber
tileset.prototype.getX = function(tilenumber) {
    return (tilenumber % this.width - 1) * this.tilesize;

// calculate Y by tilenumber
tileset.prototype.getY = function(tilenumber) {
    return Math.floor(tilenumber / this.width) * this.tilesize;

That allows you to use it like this:

var mySet = new tileset(6, 10); // width=6, tilesize=10
var x = mySet.getX(16); // tilenumber=16
var y = mySet.getY(16); // tilenumber=16

To see it in action, check this FIDDLE.

Please note that it calculates the position of top left corner. It can be adjusted otherwise if needed.

Hope this helps!