+1 vote

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.


in Engine by (13 points)

1 Answer

+1 vote

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.

by (629 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.