Tilemap with multiple layers using 2D arrays

Hello, I’m new to Phaser, still trying to figure out the fundamentals of Tilemaps.

One thing I can’t figure out despite hours of research and trial and errors, is to create a tilemap containing multiple data layers, created from arrays.

Consider the following arrays (reduced size for the sake of the discussion):

const data1 = [
  [1, 1, 1, 1],
  [1, 0, 0, 1],
  [1, 0, 0, 1],
  [1, 1, 1, 1],
];

const data2 = [
  [0, 0, 0, 0],
  [0, 0, 2, 0],
  [0, 0, 2, 0],
  [0, 0, 0, 0],
];

Consider that these will be procedurally generated, so using Tiled is out of the question.

How would I go about and create a single tilemap object that contain 2 layers, each with a different data array?

Importing from Tiled allows for multiple layers so I’m pretty sure it is possible to do it in a more dynamic way, only exemples seem to be non-existent. So far the exemples I’ve seen only provide one array at initialization:

scene.make.tilemap({
  data: [...],
  tileWidth:32,
  tileHeight:32,
});

This effectively creates one layer with the provided data.

At this point, I’ll probably create as many tilemaps as I have data arrays, and visually align them to get the same effect. However it feels like that would not be the best approach, given the capabilities of Tilemaps.

Thank you.

This amazing procedural tilemap tutorial may help out. It uses a library called Dungeon.js to generate the dungeons it is using but I think you can still learn quite a bit from it. It appears that there are other ways of making tilemaps that don’t require you to pass in a single array into the data attribute. From there you should be able to make the layers separately.

It may take a bit of work to translate this tutorial (which is using Dungeon.js, dynamic layers and some other things you may not want) to work for your usecase but I think it should be able to get you moving at least. There is a point in the tutorial where he is placing objects directly on a layer. Maybe at that point there will be a method you can use to simply give it an array instead.

Thanks for the answer Jackolantern, it is an awesome resource indeed. I’ve been reading through it and it is really useful.

However, it doesn’t answer my question. Like most of the tutorial I’ve seen that cover procedural tilemaps, it only uses a single data source (in this occurence coming from the dungeon generator). It uses 2 dynamic layers, but they are manually populated by looping through the dungeon data. What I’m looking for is really a way to give the tilemap a predefined array and have a layer automatically generated from that.

Still a good source for inspiration.

Thank you.