In my last post, I went over how to load tileMaps in phaser 3 using arrays. It is a good method for loading small maps, but most game developers use tools like the Tiled Map editor to create large maps. When we use tools like this, we need to load the map from a JSON file.
I won’t go over how to use the software because it is fairly easy to use, but if you need help, there are tons of videos on it, including mine.
Loading the JSON
There are two steps in preloading for the tileMaps. The first is to load the tiles themselves, the actual images. Place this code in your preload function.
this.load.image("tiles","src/assets/tiles.png");
The next step is to load the JSON file. This contains all the information assembled by the software of positioning and layering.
this.load.tilemapTiledJSON('map',"src/assets/map1.json");
Making the map
Next we need to make a map object to hold everything. The key is the preload cache key that was set in the code above. The tileWidth and tileHeight must be specified.
const map = this.make.tilemap({ key: "map", tileWidth: 64, tileHeight: 64});
Next make a tileset object with the key we used to load the images. This will break the spritesheet into an array of images for the map to use.
const tileset = map.addTilesetImage("tiles1","tiles");
The last step is to make a layer. The layer name can be found in the tileSet program in the LAYERS pane. You will need to make this code for every layer of the map you want to add to the game.
Different layers can be useful for organization and for setting depth or collisions. Examples might be a layer of treasure or a layer of clouds. My next post will cover layers in more detail.
const layer = map.createLayer("toplayer", tileset, 0, 0);
Here is the entire code:
export class SceneMain extends Phaser.Scene {
constructor() {
super("SceneMain");
}
preload() {
this.load.image("tiles","src/assets/tiles.png");
this.load.tilemapTiledJSON('map',"src/assets/map1.json");
}
create() {
const map = this.make.tilemap({ key: "map", tileWidth: 64, tileHeight: 64});
const tileset = map.addTilesetImage("tiles1","tiles");
const layer = map.createLayer("toplayer", tileset, 0, 0);
}
update() {
}
}
export default SceneMain;
If you’ve any questions on loading tileMaps in Phaser 3, just use the contact form or leave a comment below.