Hello world for the first time famed stack overflow!
I am parsing a Tiled-made .json map(just a test) from Reading JSON Tiled map editor file and displaying to canvas
I don't fully understand the renderLayer function, and if advisable will open a new question on that. From my rough understanding it renders each layer by tile and pushes to the final "scene" img that will be drawn.
My question specifically is how to draw a "player" object between layers. I have a Top, Middle, and Bottom layer. The middle layer is empty and where I intend to draw the player in order to add depth. I don't know where in the code to add my player update function, and I also feel like having a player update function inside the map rendering is not very OOP..
In comments is how I can get the layer name, and I have a player update function that will handle drawing.
Thanks in advance for any suggestions\explanation.
Code for the rendering the map:
$(function() {
var c = document.getElementById("canvas").getContext('2d');
scene = {
layers: [],
renderLayer: function(layer) {
/*
if(layer.name == "Middle"){
player.update();
}
*/
if (layer.type !== "tilelayer" || !layer.opacity) { return; }
var s = c.canvas.cloneNode(),
size = scene.data.tilewidth;
s = s.getContext("2d");
if (scene.layers.length < scene.data.layers.length) {
layer.data.forEach(function(tile_idx, i) {
if (!tile_idx) { return; }
var img_x, img_y, s_x, s_y,
tile = scene.data.tilesets[0];
tile_idx--;
img_x = (tile_idx % (tile.imagewidth / size)) * size;
img_y = ~~(tile_idx / (tile.imagewidth / size)) * size;
s_x = (i % layer.width) * size;
s_y = ~~(i / layer.width) * size;
s.drawImage(scene.tileset, img_x, img_y, size, size, s_x, s_y, size, size);
});
scene.layers.push(s.canvas.toDataURL());
c.drawImage(s.canvas, 0, 0);
}else {
scene.layers.forEach(function(src) {
//console.log(scene);
var i = $("<img />", { src: src })[0];
c.drawImage(i, 0, 0);
});
}
},
renderLayers: function(layers) {
layers = Array.isArray(layers) ? layers : this.data.layers;
layers.forEach(this.renderLayer);
},
loadTileset: function(json) {
this.data = json;
this.tileset = $("<img />", { src: json.tilesets[0].image })[0]
this.tileset.onload = $.proxy(this.renderLayers, this);
},
load: function() {
return $.ajax({
url: "map.json",
dataType: "text json"
}).done($.proxy(this.loadTileset, this));
}
};
scene.load();
});
renderMap = function(){
scene.renderLayers();
}