feat(#8): fix 2d camera support

This commit is contained in:
Juan Sebastián Montoya 2024-09-13 23:30:28 -05:00
parent 07c64eadeb
commit c1fe3acc11
5 changed files with 103 additions and 36 deletions

View file

@ -1,4 +1,4 @@
import { COLS, ROWS, TILE_SIZE } from "../constants.js";
import { TILE_SIZE } from "../constants.js";
import { createCanvas } from "../utils.js";
import { GameObject } from "./game-object.js";
@ -22,22 +22,20 @@ export class Map extends GameObject {
if (this._level) {
return this._level;
}
const levelConfig = this.levelConfig;
const layer = levelConfig.layers[0];
const { data, height, width } = layer;
const { ctx, canvas } = createCanvas(width * TILE_SIZE, height * TILE_SIZE);
const { ctx, canvas } = createCanvas(COLS * TILE_SIZE, ROWS * TILE_SIZE);
for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
if (row < 0 || col < 0 || row >= height || col >= width) continue;
const image = this.image;
const width = this.width;
const level = this.levelConfig;
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;
const tile = data[row * width + col] - 1;
ctx.drawImage(
image,
(tile * TILE_SIZE) % width,
Math.floor((tile * TILE_SIZE) / width) * TILE_SIZE,
this.image,
(tile * TILE_SIZE) % this.width,
Math.floor((tile * TILE_SIZE) / this.width) * TILE_SIZE,
TILE_SIZE,
TILE_SIZE,
col * TILE_SIZE,
@ -47,13 +45,25 @@ export class Map extends GameObject {
);
}
}
return (this._level = canvas);
}
render(ctx) {
render(ctx, sourceX, sourceY, width, height) {
if (!this.levelConfig || !this.selected) {
return;
}
ctx.drawImage(this.level, 0, 0);
ctx.drawImage(
this.level,
sourceX,
sourceY,
width,
height,
0,
0,
width,
height
);
}
}