How to check if something is inside of an area2d

Godot Version

4.6

Question

How do I check if something is in an area instead of checking if something entered or exited the area? I originally was suggested to use has_overlapping_bodies but I don’t know how to use that and I’ve tried looking up how to use it and didn’t find anything helpful.

If you want to know if anything is inside an area, call has_overlapping_bodies() or has_overlapping_areas().

If you want to check for one specific node, you can call overlaps_body() or overlaps_area().

1 Like
class_name Something extends CollisionBody2D
func _check_overlaps() -> void:
	var overlapping: Array[Node2D] = get_overlapping_bodies()
	for node: Node2D in overlapping:
		if node is Something:
			do_stuff()
1 Like

Awesome, that works, but how do I check if it isn’t overlapping?

Check if it’s overlapping. If it’s not overlapping - then it isn’t overlapping.

6 Likes
func _check_overlaps() -> void:
	if get_overlapping_bodies().is_empty():
		do_stuff()
1 Like

It appears not to be working. Is it my placement?

func _check_overlaps():
	var overlapping: Array[Node2D] = get_overlapping_bodies()
	for node: Node2D in overlapping:
		if node is Player
			if get_overlapping_bodies().is_empty():
				print("Out")
			else:
				print("In")

Yeah, it doesn’t make sense to check if get_overlapping_bodies().is_empty(): inside a for-loop iterating through get_overlapping_bodies() - if there’s nothing overlapping, that line can’t be reached.
You have to put it outside of the for-loop:

func _check_overlaps():
	var overlapping: Array[Node2D] = get_overlapping_bodies()
	if overlapping.is_empty():
		print("Out")
	for node: Node2D in overlapping:
		if node is Player:
			print("In")

If your area can detect anything else than the player, get_overlapping_bodies() might not be empty though. In that case you could use a bool instead: Initialize it as false and set it to true if a player is found in the for-loop.

func _check_overlaps():
	var overlapping: Array[Node2D] = get_overlapping_bodies()
	var is_player_inside := false
	for node: Node2D in overlapping:
		if node is Player:
			print("In")
			is_player_inside = true
	if not is_player_inside:
		print("Out")
2 Likes

Yeah you’ve conflated the two code examples I’ve given you.

1 Like

This is actually the best/easiest way I can do it, in my opinion. Thank you very much!

Apologies for reopening this, but the only problem is it keeps printing “Out Out In Out Out,” meaning that the player is not being registered in the area even though the player is. How do I fix that?

From where and how often are you calling this function? Are there multiple areas with this script attached, each printing their individual result?

1 Like

Yep, that was the problem. I didn’t realize that the other areas weren’t disabled, so I fixed it by setting their process mode to disabled and then set one of them to inherit when the game starts. Apologies, but thank you for your assistance.