How to know the position of a body that entered an area2d every frame while it's still inside the area2d then switch to tracking another once the previous one exited?

Godot Version

4.3

Question

There will be instantiated scenes with characterbody2d as their root node and once they enter the area2d, I want to keep track of the position of the body that entered first (in every frame) and once it exited, I want to switch the position tracking to another one and also track its position in every frame while it is still inside the area2d. How do I approach this?

Create a variable to store the body that entered the area, get it with body_entered signal.
set the value of your variable to be null when it exits the area. use the body_exited signal.

On the _process() function you can verify if your variable has a value different than null, and there you can do what you want.

If performance matters, you can avoid checking collisions by just checking the object position.
You define an area with min_width, max_width, min_heigth and max_heigth, where these variables will represent vertices of a rectangle and you verify on _process()
if basis.x > min_width and basis.x < max_width and basis.y > min_heigth and basis.y < max_heigth. Note that this doesn’t work if your area is different than a rectangle, if so, it’s better to keep using Area2D.

1 Like

Your second suggestion though, it feels like I’ve been enlightened lol. Anyways, thank you very much!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.