0 votes

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

Godot version 3.3.2
in Engine by (188 points)

1 Answer

0 votes
Best answer

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

by (4,478 points)
selected by

Can you explaine how to accomplish this

  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

Thanks bro it helped alot

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 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 webmaster@godotengine.org with your username.