How to get max/min coordinates from an array of Vector2?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By _bjork

I am looking for a way to get the maximum (the most positive) and the minimum (the most negative) Vector2 coordinates from a given array “_bufferTileList”. Say we have:

[(-1, 0), (-1, 1), (0, 0), (0, 1), (1, 0), (1, 1)]

In this scenario, the most positive would be (1, 1), or the furthest away from (0, 0) that is in the 1st quadrant, and the most negative would be (-1, 0), or the furthest away from (0, 0) that is in the 3rd quadrant.

The coordinates inside “_bufferTileList” will always have a rectangular layout.

Originally I expected it to be really easy, something like:

func _getMinVector2FromArray(_arr:PoolVector2Array) -> Vector2:
	var min_val:Vector2 = _arr[0]
	for i in range(_arr.size()):
		if min_val > _arr[i]:
			min_val = _arr[i]
	return min_val

This quite literally compares if a vector (it’s length) is smaller than the first one, which would only work if we’re working in one quadrant (e.g. 1st quadrant).

My next approach was to split all the coordinates from their quadrants and from there get the coordinate with the maximum distance from (0, 0). However the contents of the array could all be located in the same quadrant. I then thought that i would have to transpose the x/y axis to the center of the selection, but it would not work with arrays in which width or height is even.

I am pretty sure there is a more simpler, easier approach to all of it.

Is there any built-in method to do this?
Is there a better approach?

I think we need to clarify the definition: Are you only concerned about the first and third quadrants when you define ‘most positive’ and ‘most negative’? What about the other quadrants, e.g. is (-1, 1) more or less negative/positive than (1, -1)?

bridsy | 2021-10-12 22:49

:bust_in_silhouette: Reply From: max.marauder

How about creating a Rect2 with the 1st vector as position and (0, 0) size, and then sequentially expanding it with the rest of the vectors using Rect2 expand method?
I think position and end of the resulting Rect2 will be the values you seek.

This is exactly what I was looking for. As a Godot newbie I had no idea this existed. Thanks a lot!

_bjork | 2021-10-12 23:15

1 Like