0

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • The simplest solution is to cut Y axis into 10px parts and randomly create trees for each part in order you need. I haven't heard of indexing in canvas cuz you are drawing trees on top of each other. So you need to create order of creation. First 10 trees in row 1 then 7 in row 2 etc. – Mortimer Mar 08 '20 at 19:41
  • We don't do "SOLVED" or "RESOLVED" in the titles here. If you have an answer of your own post it below, but not in your question please. – j08691 Mar 10 '20 at 17:06

1 Answers1

0

Essentially, you want to render the trees in order of their y-coordinate. It sounds like your y-axis is pointing upwards, so you will need to render the trees with the highest y-coordinate first. That way, trees further down the screen will be rendered on top.

One simple way to do this is to sort your array of trees. You can do this every frame (acceptable if you have very few trees), or maintain a sorted array over time. In the latter case, there are multiple techniques for how to insert new trees:

  1. Search through the array linearly until you find the correct index
  2. Perform a binary search to find the correct index

Instead of inserting new trees at the end of the array every time, you want to find the correct "sorted" location. There is a lot of information about these techniques online. I can refer you to this other post with a great answer that you may find interesting:

How can I push an element into array at a sorted index position?