Inconsistent 2d collider hit registration
I'm working on a simple melee system and I'm getting very inconsistant hit registration. here is my Attack Trigger code
using UnityEngine;
using System.Collections;
public class AttackTrigger : MonoBehaviour {
public int dmg;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Enemy")
{
col.gameObject.SendMessageUpwards("Damage", dmg);
Debug.Log("Swing");
}
}
}
Enemy code:
public class Enemy : MonoBehaviour {
public int health;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (health <= 0)
{
Destroy(gameObject);
}
}
public void Damage(int damage)
{
health -= damage;
//gameObject.GetComponent<Animation>().Play("name");
Debug.Log("Hit");
}
}
Player attack code:
public class PlayerAttack : MonoBehaviour {
Rigidbody2D rbody;
Animator anim;
public Collider2D hitbox;
private bool Attacking = false;
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
hitbox.enabled = false;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
if (!Attacking)
{
hitbox.enabled = true;
anim.SetTrigger("Attack");
Attacking = true;
}
else
{
Attacking = false;
hitbox.enabled = false;
}
}
else
{
Attacking = false;
hitbox.enabled = false;
}
}
}
Here's a visual gif of whats happening https://i.gyazo.com/28f584c42cb0c33c447d6e6de50d813c.gif
Thanks for any help.
Answer by zachmallet · Oct 18, 2016 at 04:53 PM
I changed my code to call the animation on click then enable the hitbox from the animation itself. Solving all the issues I was having.
Answer by jahester · Oct 18, 2016 at 02:03 AM
I had a sort of a similar problem recently and it turned out to be due to two different scripts looking for a collider hit on the same gameobject. I my case it was an icon to toggle a GUI menu open or closed. When the wrong script intercepted the hit first, the menu would stay in its current state and it appeared nothing was happening. I added a static boolean to keep track of which of the two colliders should be active based on the current state of the menu.
Answer by DevilZ1976 · Oct 18, 2016 at 04:27 PM
First question why don't you use GetComponent instead of SendMessageUpwards on your collider gameobject?
And why do control attack on mousedown, don't you need any cooldown for next attack?