How do I measure the distance to the nearest duplicate of an object?

Godot Version

v4.7.2

Question

Hello

I’m trying to make a sort of game/physics simulation hybrid, and I need to somehow measure the distance from each individual duplicate of an object to the closest duplicate of the same object. I have no idea how to go about this, or if it’s realistically possible, so any help would be greatly appreciated!

Thanks :smiley:

Put every object of same class in an array.

Set var distance to a high starting value. For each object, get distance to object 1, if b->a distance is lower then var distance, set new var distance value. You can combine the index to store it as well.
At the end you have the nearest distance and the index of the object in array to access it.

as @andi_godot said you just need to iterate (it’s best method if you don’t know where is your object and have no reference to it)

var objects = {}

func nearest_object(pos):
  var previous_object
  for object in objects:
    var object_pos = object.position
    var distance = (pos - object_pos).length()
    var past_distance = (pos - previous_object.position).length()
    if distance < past_distance:
      previous_object = object
  return object

That’s unless you know the reference, e.g let’s say you have your object and reference to duplicate like:

extends Node2D
class_name Object

var duplicate = null

you can just do normal distance-check

func get_distance(object):
  return (object.position - object.duplicate.position).length()

also if you have some sort of type and decide to use first function you might need to add some if statements or match but that’s up to what you want

It depends on the amount of objects you want to check on every frame. It’s not a linear problem (if you want to know it for every copy, too), with a lot of objects the calculation will explode. It’s the classic nearest neighbor problem.

With a lot of objects you’ll need some sort of tree search or spatial grid to speed it up.