83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
import { doRectanglesOverlap } from "./util.js"
|
|
export default class Room {
|
|
constructor(json, name) {
|
|
this.json = json
|
|
this.name = name
|
|
}
|
|
|
|
tick(game, dt) {
|
|
this.json.layers.forEach(layer => {
|
|
if (layer.type == "objectgroup") this.tickObjectGroup(game, layer)
|
|
})
|
|
}
|
|
|
|
tickObjectGroup(game, layer) {
|
|
const { player } = game
|
|
layer.objects.forEach(object => {
|
|
if (doRectanglesOverlap(player, object)) {
|
|
const eventName = object.properties.find(property => property.name == "event")?.value
|
|
if (eventName) game.triggerEvent(eventName, object)
|
|
}
|
|
if (player.interactHitbox && doRectanglesOverlap(player.interactHitbox, object)) {
|
|
const eventName = object.properties.find(property => property.name == "interactEvent")?.value
|
|
if (eventName) game.triggerEvent(eventName, object)
|
|
}
|
|
})
|
|
}
|
|
|
|
get tilesetsToLoad() {
|
|
const ts = {}
|
|
this.json.tilesets.forEach((tileset, index) => {
|
|
ts[`${this.name}-${index}`] = tileset.source
|
|
})
|
|
return ts
|
|
}
|
|
|
|
populateTilesets(assets) {
|
|
console.log(this.json)
|
|
this.tilesets = this.json.tilesets.map((tileset, index) => {
|
|
const ts = assets.get(`${this.name}-${index}`)
|
|
ts.populateImage(assets)
|
|
return ts
|
|
})
|
|
}
|
|
|
|
draw(ctx) {
|
|
this.json.layers.forEach(this.drawLayer.bind(this, ctx))
|
|
}
|
|
|
|
drawLayer(ctx, layer) {
|
|
if (layer.type == "tilelayer") this.drawTileLayer(ctx, layer)
|
|
else if (layer.type == "objectgroup") this.drawObjectGroup(ctx, layer)
|
|
}
|
|
|
|
drawTileLayer(ctx, layer) {
|
|
for (let y = 0; y < layer.height; y++) {
|
|
for (let x = 0; x < layer.width; x++) {
|
|
const index = x + (y * layer.width)
|
|
const tileIndex = layer.data[index] - 1
|
|
const tileset = this.tilesets[0]
|
|
const [sx, sy] = tileset.tileOffset(tileIndex)
|
|
ctx.drawImage(
|
|
tileset.image,
|
|
sx,
|
|
sy,
|
|
tileset.tileWidth,
|
|
tileset.tileHeight,
|
|
x * this.json.tilewidth,
|
|
y * this.json.tileheight,
|
|
this.json.tilewidth,
|
|
this.json.tileheight
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
drawObjectGroup(ctx, layer) {
|
|
layer.objects.forEach(object => {
|
|
ctx.fillStyle = object.properties.find(property => property.name == "color").value
|
|
ctx.fillRect(object.x, object.y, object.width, object.height)
|
|
})
|
|
}
|
|
}
|