Forum begins after the advertisement:


[Part 3] Enemies with multiple colliders get hit multiple times

Home Forums Video Game Tutorial Series Creating a Metroidvania in Unity [Part 3] Enemies with multiple colliders get hit multiple times

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #13173
    Terence
    Level 30
    Keymaster
    Helpful?
    Up
    0
    ::

    Here’s a question from @Jiyo on YouTube which I feel is worth looking at:

    there are 2 box colliders in the enemy, then it is hit twice by an attack, is there any way to fix this? Also, my enemy doesn’t move linearly but moves by bouncing.
    #13174
    Terence
    Level 30
    Keymaster
    Helpful?
    Up
    0
    ::

    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<Enemy>() != 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.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: