How do I detect when a body is inside an Area2D? (inside, not entered)

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

Hello! I’m a beginner and I’m making an RPG-type game to test out the engine.

I have an Area2D around the player to detect when an enemy is close enough to reach and attack, and I have another, bigger Area2D around the enemies to detect when the player is nearby and start following/attacking him

My problem:
I made it so the enemies spawn at random coordinates(when one enemy dies, another is spawned), and sometimes they spawn too close to the player and it doesn’t detect the body_entered and body_exited because the body is already inside. So the enemies don’t follow me and I can’t attack them.

Any ideas on how I can fix this?

Can you show your script so that I can help please? | 2021-01-15 23:10

:bust_in_silhouette: Reply From: exuin

Area2D has a method for getting all overlapping areas. Just call it when the enemy is spawned and check if the one of the areas it overlaps is the player’s.


Player should be a characterbody. This will take care of most collision it is very practical.
Then like exiun said, you must check the list of overlapping object within the area of the enemy, as it will detects all collision types…all you have to do is check if it is a body. Actually in the player side, if you do have a scene for the player and attach a script to the root node and define a class_name, you will be able to reference this body type by the classe name.

func _on_body_exited(body: Node2D) -> void:
	if body is Player:
		body.in_duck_area = false
		print("area exited")
	pass # Replace with function body.

like the example there, the event of exiting the area fires and inside it I check what has left the area and do something with it.
inside my character there is a script attached to it and a definition there

class_name Player

That way it is easy to detect what has collided in the area, or better saying what has overlapped.