Check distance between points in array

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

Hello!

I have an array of Vectors2. The size of the array goes from 0 (empty) to 3.

I want to check If any 2 points inside it exceed a given maxDistance and then turn a variable false (ex.: allowShoot = False).

I know I have the distance_to method but I don’t know how to construct the loop to make that (if a loop it’s what I need I mean).

Thank you very much!

Distance towards what? You mean, if any point is further than any other point by a given distance? Or is it distance towards the same point?

Zylann | 2019-12-04 21:20

:bust_in_silhouette: Reply From: Saitodepaula

I understood you are working in 2D. I have only worked in 3D, but it should be almost the same:

var PlayerPos = self.get_global_transform().origin
var PointsArray = [Vector2(0, 0), Vector2(5, 5)]

for Point in PointsArray:
	var DistanceToPoint = PlayerPos.distance_to(Point)
	
	if DistanceToPoint > 10:
		allowShoot = false

ORIGIN is a property of TRANSFORM, and is a Vector2 in 2D and a Vector3 in 3D. Since you already have a position in Vector2 format, you just need your player position in Vector2.

:bust_in_silhouette: Reply From: null_digital

I don’t know if there’s an engine method to check distances in an array of vectors. But here’s a loop to check each frame if any of the distances within an array exceeds a value:

func _process(delta):
var vector_array = []
var maxdistance = 100.0
for idx in range(0, vector_array.size()-2):
	var p0 = vector_array[idx]
	var p1 = vector_array[idx+1]
	if p0.distance_to(p1) > maxdistance:
		allowShoot = false
		break
pass

EDIT: previous loop range could crash the game, fixed it.

This worked perfectly thank you!!!

And sorry to the other people commenting for not explaining myself well enough!

hermo | 2019-12-05 09:39