most efficient way to detect nearby objects + implement "sight" for enemies?

Godot Version

Godot v4.2.1

Question

hey hey - so im very new to godot, as in i started 3 days ago. but ive got things like basic movement, etc, down and im just wondering - would it be possible to implement some kind of “radius” around a player or enemy that determines what they see?

for enemies, i would use this for player detection, although im not sure how the switch from passive->aggressive mode would work i imagine it would be some kind of signal. for players, this would be so they could select or interact with objects if they got close enough. my initial idea was some kind of invisible object that is attached to whatever it needs to be attached to and it would detect anything that enters it, but ive heard RayCast2D might be good - i do not know how to use RayCast2D though [i think thats the name, anyway]. just looking for suggestions! i hope this isn’t too vague. thanks in advance for anyone that wants to help!

You could use a CollisionObject2D + circle collision shape for your initial aggro range, and then use a ray to determine if there’s line of sight.

AI state can be done with a state machine, which you can implement with a state enum and a class or node for the state (there are many more ways to slice it with a few tutorials on yt).

Once you have a collision in your radius, a signal will fire, where you can determine if the AI state should change. You could test your ray as part of that determination. There’s a bit of boilerplate to get a ray going with code. Or you could use a RayCast2D on the player that you activate/deactivate, modify, and use for this case.

Of course, you could do all of this with code instead of native collisions as well, getting distance_to between the objects on the physics update. But it’s probably better to use native nodes and let the engine optimize the problem.

4 Likes

it would be cool for adding a passive-aggresive state to enemies, kinda like Goombas in Mario Maker 2 in the 3D World game style