Skip to content

Loading a TiledMap

Caldas Lopes edited this page Oct 24, 2021 · 3 revisions

loadTiledMap

Syntax

method loadTiledMap
param  {String}   mapName               Map name.
param  {String}   [imagePath]           Path to the image file(s). Default: "/".
param  {Number}   [transparentOffset]   Maximum difference on RGB channels to apply Tile transparency. Default: 4.
param  {Function} [callback]            Name of a function to call once map loads.
return {p5.TiledMap}

Information

loadTiledMap() returns a new p5.TiledMap.

TiledMap uses Tiled JavaScript export, which must be loaded previously:

<script language="javascript" type="text/javascript" src="data/desert.js"></script>

External TileSets are not supported, because they are not part of the exported javascript script.

If called during preload(), the p5.TiledMap will be ready to play in time for setup() and draw().

function preload() {
    tmap = loadTiledMap("desert", "data");
}

function setup() {
    createCanvas(800, 600);
}

function draw() {
    background(128);
    tmap.draw(0, 0);
}

If called outside of preload, the p5.TiledMap will not be ready immediately, so loadTiledMap accepts a callback as the last parameter.

var tmap;

function setup() {
  createCanvas(800, 600);
}

function draw() {
  background(128);
  if(tmap) tmap.draw(0, 0);
}

function keyPressed(){
  loadTiledMap("desert", "data", mapLoaded);
}

function mapLoaded(newMap) {
  tmap = newMap;
  console.log(tmap.getMapSize());
}

You can still use loadTiledMap without a callback,

function keyPressed(){
  tmap = loadTiledMap("desert", "data");
}

but it's not advised due to the asynchronous nature of javascript.