- Home /
The question is answered, right answer was accepted
weapon collider
Hi: I'm trying to make the player attacking an enemy by his weapon during the player's attack animation, i use a collider which attached to player's weapon to detect the enemy . i found that the enemy takes the damage twice, i'm not sure this happened it is because the enemy have two colliders or what. what i want is the enemy will take damage only if the enemy's capsule collider is touched by player's weapon and at a specific frame of the player attack animation. the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwordAttack2 : MonoBehaviour {
private int _playerAttackStateHash = Animator.StringToHash("Base Layer.Attack2");
Animator _animator;
public int swordDamage = 30;
RaycastHit hit;
GameObject enemy;
EnemyHealth enemyHealth;
bool enemyinRange = false;
void Awake () {
_animator = GetComponentInParent<Animator>();
enemy = GameObject.FindGameObjectWithTag("Enemy");
enemyHealth = enemy.GetComponent<EnemyHealth>();
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy"))
{
enemyinRange = true;
AnimatorStateInfo info = _animator.GetCurrentAnimatorStateInfo(0);
if (info.nameHash == _playerAttackStateHash && enemyinRange == true)
{
enemyHealth.TakeDamage(swordDamage, hit);
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == enemy)
{
enemyinRange = false;
}
}
}
if anyone can help me with this, please? thank you!
Try adding a float invulnTime;
to the EnemyHealth script; during the Update() of enemyHealth, have invulnTime -= Time.deltaTime;
; and when TakeDamage is called, have a check like
if( invulnTime >= 0 )
{
invulnTime = 0.5f; // Or however many seconds you want the enemy to be invulnerable for during the attack.
// Run all your damage scripts;
}
This'll let you know if it's hitting multiple times because it's hitting multiple colliders in a short amount of time.
Thank you ! It works great! but just one little problem, i think the script should be like this :
takedamage(){
invulnTime = 0.5f;
if( invulnTime >= 0 )
{
// Run damage scripts;
}
}
Answer by Davirtuoso · Apr 18, 2017 at 10:35 AM
In your OnTriggerEnter method, add a check that checks the type of collider it is impacting and wrap your current code within it. Only run the code if the type is capsule collider, otherwise ignore. Something like this might work at the start (untested):
if (other.GetType() == CapsuleCollider)
{
// your current code here
}
I'm afraid I haven't used the animator much so I can't help with the specific-frame part of your question, though hopefully you'll be able to find that out/figure that part out. I hope this helps :)
Thank you! that is another good way to do the job. i didn't know how to deal with multiple colliders before you show me. it helps.
Not a problem, i'm glad it helped you. Good luck with your development!