Take damage when we hit enemy collider with weapon collider

Instead of using range i was thinking about giving damage when weapon hits enemies collider. I have put a box collider around players weapon and set it to is trigger. Then in fighter script i have added this code in the hit event. Here I pass inn the target, damage and gameobject to a function i have added in the weapon script.

if(target.gameObject.name == "Player")
                 {
                     currentWeapon.value.GiveMeeleDamage(target, damage, gameObject);
                 }
                 
                else if (target.gameObject.name != "Player" && Input.GetKeyDown(0))
                 {
                     currentWeapon.value.GiveMeeleDamage(target, damage, gameObject);
                 }

Then in the weapon script i set the target, damage, instigator and a boolean that we are hitting the enemy to true. I set this to true when we swing the sword and false after we have given damage so we cant give damage to enemy just by touching him with the sword. But the problem is that if I swing the sword without being close enough to the enemy the boolean is set to true and if i then run up to the enemy i give damage if the box collider around the sword touches the enemy without swinging. Any ideas how i can work around this?

public void GiveMeeleDamage(Health target, float damage, GameObject instigator)
        {
            this.target = target;
            this.damage = damage;
            this.instigator = instigator;
            hasHit = true;


        }

        // gives damage when weapon hits target.
        private void OnTriggerEnter(Collider other)
        {
            // since target is of type health can check if its targets health we are hitting. 
            if (other.GetComponent<Health>() != target) return;
            // if we dont have a target just stop, dont get null reference error.
            if (target == null) return;
            if (target.IsDead()) return;

            // has hit is only true if hit weapon animation reaches hit in fighter script, only then give dmg.
            // so we dont give damage when player or enemy only touches the other weapon.
            if (hasHit)
            {
                target.TakeDamage(instigator, damage);
                hasHit = false;
            }

        }

I find that collider based melee is about as reliable as Lucy holding the football for Charlie Brown. That being said, it is an option, and it’s used in another course I support, Third Person Combat and Traversal.

What you need to do is create a pair of Animation Events inside the animations that your Fighter component will use to turn the collider on and off. When I use this setup, I create these AnimationEvents

void ActivateWeapon()
{
     weaponCollider.enabled=true;
}

and

void DeactivateWeapon()
{
    weaponCollider.enabled=false;
}

Ok you convinced me not to go down that path, thnx!

Privacy & Terms