I'm generating a random "map" like so:
generateTiles() {
for (let x = 0; x < this.width; x++) {
for (let y = 0; y < this.height; y++) {
if (Math.random() < 0.3) {
this.worldmap[x][y] = new Wall(x, y);
} else {
this.worldmap[x][y] = new Floor(x, y);
}
}
}
}
Then, I try to render it to canvas by mapping over rows & cells:
drawMap(context) {
this.worldmap.map(function(row) {
return row.map(function(cell) {
return this.drawSprite(
context,
loadSpritesheet(sprites),
cell.attributes.sprite,
cell.x,
cell.y,
this.tilesize
);
}, this);
}, this);
}
By the above only renders a single tile in a {x: 0, y:0}. When I inspect the row and cell arrays over which map is iterating they all have distinct coordinates. This implies that the generation part works fine, and the problem lies with how I loop & render the map.
I read few answers on SO about preloading images. Its something to consider for the future but as I'm only loading a single spritesheet I don't think this is my issue.
I can't figure this one out, suggestions will be greatly appreciated!
For completeness sake, here is my drawing function:
drawSprite(context, spritesheet, sprite, x, y, tilesize) {
context.drawImage(
spritesheet, // image
sprite * 16, // sx
0, // sy
16, // sWidth
16, // sHeight
x, // dx
y, // dy
tilesize, // dWidth
tilesize // dHeight
);
}
And a function loading the spritesheet:
const loadSpritesheet = src => {
const spritesheet = new Image();
spritesheet.src = src;
return spritesheet;
};
export default loadSpritesheet;
Also, here is a gist with more complete code exhibiting described problem.
EDIT:
As per @CertainPerformance suggestion, I tried nested for loop:
for (let x = 0; x < this.worldmap.length; x++) {
for (let y = 0; y < this.worldmap[x].length; y++) {
this.drawSprite(
context,
loadSpritesheet(sprites),
this.worldmap[x][y].attributes.sprite,
this.worldmap[x][y].x,
this.worldmap[x][y].y,
this.tilesize
);
}
}
Still, only a single tile is being rendered.