Solution: Every time a new tree is generated, it sorts the trees based on Y position
trees.sort(function(a, b) {
return parseFloat(a.Y) - parseFloat(b.Y);
});
So let's say I have this empty array:
trees[];
And I have a timer generating these trees with random positions.
function generateTrees() {
if(tick % 50 === 0) {
trees.push({
X: randomNumber,
Y: randomNumber,
H: 60,
W: 30,
image: treeImage
});
}
}
So it's generating trees and that goes fine. But sometimes the trees overlap when drawing them, and I'm fine with that. But the problem is, the trees generated above other trees on the Y axis will sometimes draw on top of the ones below, Here's an example. I'm trying to simulate a bird's eye 3D-ish view, so I would like to draw these objects behind the ones below it in the Y axis.
I have this drawing code, and I've tried if statements but I'm not sure how I would do it with arrays and a single number 'i':
function draw() {
for(i = 0; i < trees.length; i++) {
ctx.drawImage(trees[i].X,trees[i].Y,trees[i].W,trees[i].H);
}
}
Could anyone point me in the right direction on to how I could implement this solution? Please and thank you in advance.