How to sort an array consisting of Vector2?

Godot Version

4.3 stable

Question

I have an array of 10 Vector2. I need the variables to be sorted FIRST by y and only then by x from smallest to largest. Example

(-5, -10), (15, -10), (-16, -9) (-9, -9)

How can I do that?

Array.sort_custom() is what you want

1 Like

I have already tried to use this function, but I could not come up with a condition for the function to occur, the sorting I need.

func _ready() -> void:
	var test = [Vector2(-9, -9), Vector2(15, -10), Vector2(-16, -9), Vector2(-5, -10)]
	test.sort_custom(_organize_array)
	print(test) # [(-5, -10), (15, -10), (-16, -9), (-9, -9)]


# Not much secret, the function receive two args, you return 
# true if the first element go behind/for the right of the 
# second element
func _organize_array(p_element_1: Vector2, p_element_2: Vector2) -> bool:
	# If the y value from the first element is smaller than 
	# the y element from the second, swap their 
	# positions/send the first element to the right of second
	if p_element_1.y < p_element_2.y:
		return true
	
	# If both elemets have the same y value but the first
	# element has a smaller x value, swap their positions/send 
	# the first element to the right of the second 
	elif  p_element_1.y == p_element_2.y and p_element_1.x < p_element_2.x:
		return true
	
	# Both has the same value or the first is bigger than the 
	# second, keep their positions
	return false
1 Like

Thank you so much, this is exactly what I need.