The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes

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?

Godot version 3.3.3
in Engine by (41 points)

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)?

1 Answer

+1 vote
Best answer

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.

by (156 points)
selected by

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.