game-engine/modules/game-objects/map.js

46 lines
1.2 KiB
JavaScript

import { COLS, ROWS, TILE_SIZE } from "../constants.js";
import { GameObject } from "./game-object.js";
export class Map extends GameObject {
constructor({ name, imageId, elementId, selected = false }) {
super();
this.name = name;
this.imageId = imageId;
this.image = document.getElementById(imageId);
this.selected = selected;
this.elementId = elementId;
}
async load() {
const level = await fetch("/resources/" + this.name + ".json");
this.level = await level.json();
return true;
}
render(ctx) {
if (!this.level) {
return;
}
const levelImage = this.image;
const level = this.level;
const layer = level.layers[0];
const data = layer.data;
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const tile = data[row * COLS + col] - 1;
ctx.drawImage(
levelImage,
(tile * TILE_SIZE) % levelImage.width,
Math.floor((tile * TILE_SIZE) / levelImage.width) * TILE_SIZE,
TILE_SIZE,
TILE_SIZE,
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
);
}
}
}
}