Problem using RayCast2D in enemy to detect player

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

I think I may be following the wrong approach here…

I have an enemy which uses a RayCast2D to detect a player. The y of the cast_to does not change. The x only changes depending on the enemy flip_h (ie. if he is “looking” left or right).
If an enemy goes up a ramp and the player is at the top of this ramp (so that the RayCast2D approaches the player from below) in one frame the enemy detects the player (and starts attacking, with a change in animation) and in the next, it doesn’t (so it stops attacking and goes back to the walk animation) - creating a loop.

There is a small difference in the origin of this Raycast2D leading to the problem above, even so its position is (0,0) on the enemy.

Is there a standard solution to this problem?

:bust_in_silhouette: Reply From: TheVoiceInMyHead

If it helps anybody this is how I ended up addressing this:

When my enemy is attacking, if the “sight” RayCast2D stops colliding with the player, I make a couple of changes the RayCast2D position.x (+c and -c where c is a small constant). If there is a collision with the player the enemy keeps attacking, if not it goes to another state.