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:
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
);
}
}
By the above only renders a single tile in a {x: 0, y:0}
. When I inspect the row
and cell
arrays 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 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;