What is this sort function.
poly_partial.sort_custom(self, "_lessv_x" if is_even else "_lessv_y")
what is it trying to sort and why are we sorting it.
Thanks for the question.
It's briefly explained in the lesson, but it could use a more detailed breakdown.
In short, the code sorts the points we generate along the borders of our polygon, roughly two by two.
Let's step back through the algorithm.
We generate four rectangles along the edges of a larger rectangle.
Inside each of those rectangles, we sample some random points. We'll use them to define the room's bounds.
Now, we have to fill the polygon represented by those points. And to do so, we need the points to be in clockwise order to save the shape they form as a valid polygon in Godot. Doing so allows us to use the method:
Which will tell us if we should draw the tile we're looping over when filling the tilemap.
As we generated the four rectangles containing the points in a specific order, we know that we only need to sort the points inside each rectangle.We don't know in which order they were generated; first, we might have generated a point on the right side of a border polygon, then the one on the left. In that case, we need to swap their order.
We use Array.sort_custom() to let the sorting algorithm do that.
Either the rectangle where we generated the points is mostly vertical and we need to sort the points based on their Y position (_less_y) or the rectangle is mostly horizontal and we need to compare the X positon of the points (_less_x).
As we know we generated the rectangles in clockwise order, starting from the top, we can use their index to pick the right comparison function. The rectangles in the `order` variable at indices 0 and 2 are horizontal, and at indices 1 and 3 they're vertical.
Hence the code:
"_lessv_x" if is_even else "_lessv_y"
I hope this helps. Let me know if you have any more questions. I'll also log a task to add code comments in the older chapters of the course, like we do in more recent courses and series.