import { TILE_SIZE } from "../constants.js"; import { GameObject } from "./game-object.js"; import { Sprite } from "./sprite.js"; export class SpriteSheet extends GameObject { constructor({ imageId, x = 0, y = 0, tileWidth = TILE_SIZE, tileHeight = TILE_SIZE, offsetX = 0, offsetY = 0, }) { super({ x, y }); this.image = document.getElementById(imageId); this.imageWidth = this.image.width; this.imageHeight = this.image.height; this.tileWidth = tileWidth; this.tileHeight = tileHeight; this.offsetX = offsetX; this.offsetY = offsetY; } get sprites() { if (this.gameObjects?.length) { return this.gameObjects; } const sprites = []; let index = 0; for (let row = 0; row < this.imageHeight; row += this.tileHeight) { for (let col = 0; col < this.imageWidth; col += this.tileWidth) { sprites.push( new Sprite({ image: this.image, index, x: col + this.offsetX, y: row + this.offsetY, width: this.tileWidth, height: this.tileHeight, }) ); index++; } } return (this.gameObjects = sprites); } }