Area2D vs Raycast2D?

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

I want to make the units have an array of enemies that gets updated when the enemy is within distance (and vice versa for the enemies).

My game has my units and the enemies going in only one direction, so using Area2D’s bad because I don’t want them turning around to attack things behind them. Using Raycast2D is bad because it has no on_Collision/on_Enter signal, if I use get_collider then the enemy in front of the unit would be constantly added to the array.

How do I go about this?

(For reference, think of my game as a Battle Cats clone, as weird as that may sound.)

:bust_in_silhouette: Reply From: zhyrin

It’s a bit hard to comprehend your issue, as you bring up specific problems you came across without elaborating, but here goes.

With Area2D, you could use vector math (dot product) to see if the opponent is in front and not to the back.

With Raycast2D you can add exceptions (objects the ray shouldn’t detect). Once an opponent is detected, you can add it as an exception (and later remove it from being an exception as/if appropriate).
You can also check if an opponent is in your array before adding it to the array, circumventing duplicates.

If you want to check based on distance, Area2D with a circle shape sounds to make more sense. You can evaluate opponents in the array and if they are behind the current unit, you can just discard them from the array.
You can also make a custom shape for the Area2D that is only in front of the unit.

:bust_in_silhouette: Reply From: sante

I see you are drowning in a glass of water… Just use the raycast and check if its reference is already in the array before adding it… Don’t you think?
You can just use the “find” method of arrays verifying that it returns a value less than zero before adding the enemy to it, right?

:bust_in_silhouette: Reply From: Moreus

you can add masks or and exclude the object from raycast detection, you can change start position of raycast.