0 votes

I know it's possible to code something like this

func _on_Area2D_body_entered(body):
if body.is_in_group("somegroup"):
    print("collisions! but once...")

but the above code checks this once, I want to check it every frame.

Godot version 3.4.4
in Engine by (15 points)

2 Answers

+1 vote
Best answer

You can use either the get_overlapping_bodies() or overlaps_body(body: Node) method on the area.

func _process(delta):
    for body in area.get_overlapping_bodies():
        if body.is_in_group("somegroup"):
            print("collisions!")

You can quickly find all available methods and properties in the documentation that is built into the editor.
Simply press F1, search for "Area2D" and hit enter.

by (682 points)
selected by

It may be better to use it in _physics_process() because that's when the overlapping bodies are updated.

0 votes

Area2D has a get_overlapping_bodies method. According to the docs:

For performance reasons (collisions are all processed at the same time) this list is modified once during the physics step, not immediately after objects are moved. Consider using signals instead.

I personally use a different approach, which appears to work well, and seems to be more performant:

  • Keep a list of overlapped bodies in a local variable like _overlapping
  • Add a signal to body_entered that appends the body to _overlapping
  • Add a signal to body_exited that removes the body from _overlapping

Each frame (in _process_physics), act on everything in _overlapping, e.g.:

func _process_physics(delta): for body in _overlapping: body.take_damage()

by (72 points)
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 webmaster@godotengine.org with your username.