How do I make my enemy detect the player from a certain distance?

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

How do I make my enemy detect the player from a certain distance?
enter image description here

This is how my tree looks like

I originally tried using Raycast 2d to detect the player, but it detects not only the player, it also detects other things such as walls too.
I’d like some help on a way to do it in a more efficient way. If it matters, the game is a 2D platformer.
Thanks, if I wasn’t clear enough ask me bellow and i’ll try to explain it better.

psuedo code

distance = enemy_position.distance_to(playerposition)
if distance < trigger_distance:
    do something

razah | 2018-02-13 07:59

:bust_in_silhouette: Reply From: kidscancode

Here’s one method:

Attach an Area2D to your Enemy, and give it a circular collision shape with a radius of your desired detect distance. Then you can use the body_entered signal to detect an object entering that area and check if that object is the player.

To skip the object check, put your player on a specific collision layer, and set the area’s mask to only check that layer.

Thanks, I’m gonna try this out as soon as I can =D

Decomius | 2018-02-13 16:06