::To fix this, you can modify the Hit()
function on PlayerController
so that it ignores multiple colliders belonging to the same enemy. The highlighted portions are the added code.
void Hit(Transform _attackTransform, Vector2 _attackArea, ref bool _recoilDir, float _recoilStrength)
{
Collider2D[] objectsToHit = Physics2D.OverlapBoxAll(_attackTransform.position, _attackArea, 0, attackableLayer);
List<Enemy> hitEnemies = new List<Enemy>();
if(objectsToHit.Length > 0)
{
_recoilDir = true;
}
for(int i = 0; i < objectsToHit.Length; i++)
{
if (objectsToHit[i].GetComponent() != null)
{
objectsToHit[i].GetComponent<Enemy>().EnemyHit(damage, (transform.position - objectsToHit[i].transform.position).normalized, _recoilStrength);
}
Enemy e = objectsToHit[i].GetComponent<Enemy>();
if(e && !hitEnemies.Contains(e)) {
e.EnemyHit(damage, (transform.position - objectsToHit[i].transform.position).normalized, _recoilStrength);
hitEnemies.Add(e);
}
}
}
Basically, in the Hit()
function, we create a list to store all the enemies that have already been hit, and in the loop, before we hit the enemy, we check if the enemy is already in the list (i.e. it has already been hit). This will prevent enemies from getting hit multiple times if they have multiple colliders.