How can i constantly see if body2D entered an area2D?

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

I want the Raycast2D to change it’s rotation whenever i’m in the CollisionShape2D but i don’t understand how. I’ve tried adding a while loop to the _on_DetectionRange_body_entered and it crashes. So far I have it so that whenever i enter the collision area it changes rotation to “point” at my character, i don’t know how to do it constantly so it only does it once.

what i’ve done so far:

func _on_DetectionRange_body_entered(body):
if == "Player":
	$DetectionRange/RayCast2D.rotation = ((self.global_position - body.global_position )).angle() - 55

:bust_in_silhouette: Reply From: markopolo

Since the body_entered signal only fires once (when the body enters the area) it cannot be relied upon for constant updates. You have a few other options, though:

  1. Add a boolean that body_entered enables and a variable to track that body, and add some _process logic that updates the raycast with the body’s position when the boolean is true. You’d also have to add a body_exited to disable it when you leave the area.

  2. Add some _process logic to update the raycast to point at the first thing in $DetectionRange.get_overlapping_bodies(). Don’t forget to handle the situation where there are no overlapping bodies.

Keep in mind that in both cases, you’ll have issues if there are multiple bodies that interact with the area, so you’ll have to set up collision layers and masks appropriately such that the player is the only thing that ever collides with the area shape.