Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I have a tileset something like this:

0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16,
17, 18, 19, 20

My tileset draw code looks like this:

var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
context.drawImage(image, Math.floor(tile * tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize);

And this code draws the 5 tile, but how would I draw the 10 tile, or the 15 tile without adding tileX and tileY? I probably need something like if tile is equal to 15, then draw tile 15.

share|improve this question

2 Answers 2

I'm not sure I understand why adding tileX and tileY is a bad thing? If you want to draw the whole tileset, one way of doing it is with a couple of for loops like so.

var tileSize = 32;
var x = 10;
var y = 10;

for(var tileX = 0; tileX < x; tileX ++) {
    for(var tileY = 0; tileY < y; tileY++) {
        context.drawImage(image, tileX * tileSize,tileY * tileSize , tileSize, tileSize);
    }
}

JSFiddle Example

Just my preference, but the naming below might make things a bit more clear as well.

var tileSize = 32;
var width = 10;
var height = 10;

for(var x = 0; x < width ; x++) {
    for(var y = 0; y < height; y++) {
        context.drawImage(image, x * tileSize, y * tileSize , tileSize, tileSize);
    }
}

Hope that helps.

share|improve this answer

You can add tileX and tileY but hide them inside a function where they won't trouble you.

var drawTile = function (tile, x, y, tileSize) {
    var tileX = tile % 6; //6 is the number of tiles in each row
    var tileY = Math.floor(tile/6);
    context.drawImage(image, tileX * tileSize, tileY * tileSize, tileSize, tileSize, x, y, tileSize, tileSize);
};

Now you can draw any of the tiles just by giving its number:

var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
drawTile(tile, x, y, tileSize);
tile = 10;
x = 200;
y= 100;
drawTile(tile, x, y, tileSize);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.