Get spaced tileset images to line up correctly

This commit is contained in:
Bill Rossi 2025-06-07 15:38:35 -04:00
parent 5090003484
commit 3985bce99d
4 changed files with 20 additions and 6 deletions

View File

@ -54,7 +54,7 @@ export default class Assets {
loadTileset(name, path) { loadTileset(name, path) {
return fetch(path).then(rsp => rsp.json()).then(json => { return fetch(path).then(rsp => rsp.json()).then(json => {
return this.assetMap[name] = new Tileset(this.game, json, name) return this.assetMap[name] = new Tileset(this.game, json, name, path)
}).then(tileset => this.loadImages(tileset.imagesToLoad)) }).then(tileset => this.loadImages(tileset.imagesToLoad))
} }

View File

@ -24,6 +24,8 @@ export default class Room {
ts.populateImage(assets) ts.populateImage(assets)
return ts return ts
}) })
console.log(this.tilesets)
console.log(this)
} }
draw(ctx) { draw(ctx) {
@ -70,8 +72,15 @@ export default class Room {
for (let y = 0; y < layer.height; y++) { for (let y = 0; y < layer.height; y++) {
for (let x = 0; x < layer.width; x++) { for (let x = 0; x < layer.width; x++) {
const index = x + (y * layer.width) const index = x + (y * layer.width)
const tileIndex = layer.data[index] - 1 let tileIndex = layer.data[index] + 1
const tileset = this.tilesets[0] if (tileIndex == 1) continue
let tileset = this.json.tilesets
.sort((a, b) => b.firstgid - a.firstgid)
.find(ts => ts.firstgid <= tileIndex)
const { firstgid } = tileset
tileset = this.tilesets.find(ts => ts.source == tileset.source)
tileIndex -= firstgid + 1
const [sx, sy] = tileset.tileOffset(tileIndex) const [sx, sy] = tileset.tileOffset(tileIndex)
ctx.drawImage( ctx.drawImage(
tileset.image, tileset.image,

View File

@ -1,8 +1,9 @@
export default class Tileset { export default class Tileset {
constructor(game, json, name) { constructor(game, json, name, source) {
this.game = game this.game = game
this.json = json this.json = json
this.name = name this.name = name
this.source = source
this.tiles = json.tiles || [] this.tiles = json.tiles || []
} }
@ -30,8 +31,8 @@ export default class Tileset {
tileOffset(index) { tileOffset(index) {
return [ return [
((index % this.columns) * this.tileWidth), ((index % this.columns) * (this.tileWidth + this.json.spacing)),
(Math.floor(index / this.columns) * this.tileHeight) (Math.floor(index / this.columns) * (this.tileHeight + this.json.spacing))
] ]
} }

View File

@ -1,3 +1,7 @@
body { body {
background-color: #666; background-color: #666;
} }
canvas {
image-rendering: pixelated;
}