How to manage overlapping enemies?

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

I have multiple enemies in my 2D game. I have programmed them to run at the player when they spawn. The issue is that they will often be overlapping each other, and when the player attacks with his sword it will hit both of them. I was wondering if there is a good way to only hit one of them as opposed to both of them if they are directly on top of them. All my enemies have an Area2D and collision shape attached to them.

Thanks!

:bust_in_silhouette: Reply From: markopolo

There’s a few ways you could go about this:

  1. One option would be to make your enemies no longer overlap. You could turn them into RigidBody2Ds and then configure their collision masks and layers to no longer allow overlapping. If you actually intentionally want enemies to be able to overlap, this is not the way to go. This also wouldn’t necessarily stop the sword from hitting multiple enemies in one swing; just make it less likely.
  2. Use a boolean variable to track if the sword has hit anything during its current swing. Every time a collision is detected, check to make sure this is the first thing you’ve hit before processing the consequences. Reset the variable after the swing finishes. This probably means using the sword’s collision signals instead of the enemies’ collision signals.

There’s probably other ways to do this as well, these are just two options that came to mind.