PhysicsBody in Range

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

I want to get a array of all physicsBody within certain range…
So that i can process them and choose the closest one.
If you know any other option to find closest physics body from player’s position
…please consider replying

:bust_in_silhouette: Reply From: Wakatta

There are many ways to achieve this.
The easiest being to use the area node then compare the distances of all overlapping_bodies

Can you explaine how to accomplish this

Vikrant | 2021-06-07 08:28

  1. Connect the body_entered, body_exited signals of the area node
  2. Add/Remove bodies to an array/group
var bodies

func _on_body_entered(body):
    bodies.append(body)
func _on_body_exited(body):
    bodies.remove(body)
  1. Loop through that array or group to find the closest node
func find_closest():
    var closest = bodies[0]
    for body in bodies:
        var old = closest.global_transform.origin.distance_to(global_transform.origin)
        var new = body.global_transform.origin.distance_to(global_transform.origin)
        if new < old:
            closest = body
    return closest

Wakatta | 2021-06-07 11:06

Thanks bro it helped alot

Vikrant | 2021-06-07 15:58