I’m writing a game about a cat attacking a rat.The cat has a collider and trigger, which is turned off, and is turned on only one frame when the cat starts attacking.The rat also has a collider.Both have scripts and rigidbody.OnTriggerEnter (dealing damage, collision detection) does not always work.The attack animation is done but the method does not detect any collisions.Sometimes it works sometimes not.Unity version:2018.4.2f1
Script cat:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KittyScript : MonoBehaviour
{
public BoxCollider trigger;
private float moveVertical;
private float moveHorizontal;
private Animator anim;
public float attackwait=0;
private bool attack=false;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
attack = false;
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
moveVertical = Input.GetAxis("Vertical");
moveHorizontal = Input.GetAxis("Horizontal");
anim.SetFloat("MoveVertical", moveVertical);
anim.SetFloat("MoveHorizontal", moveHorizontal);
trigger.enabled = false;
if (moveVertical > 0 && Input.GetKey(KeyCode.LeftShift)) //run
{
anim.SetBool("Run", true);
transform.Translate(new Vector3(0, 0, 3) * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space)) //jump
{
anim.SetTrigger("Jump");
}
}
else if(moveVertical>0) //walk
{
transform.Translate(new Vector3(0, 0, 1) * Time.deltaTime);
anim.SetBool("Run", false);
}
else if(moveVertical<0) //walk back
{
transform.Translate(new Vector3(0, 0, -1) * Time.deltaTime);
anim.SetBool("Run", false);
}
else
{
anim.SetBool("Run", false);
}
if (moveHorizontal>0) //turn right
{
transform.Rotate(new Vector3(0, 70, 0) * Time.deltaTime);
}
else if(moveHorizontal<0)//turn left
{
transform.Rotate(new Vector3(0, -70, 0) * Time.deltaTime);
}
if (attackwait <= 0) //wait for attack
{
if(attackwait<0)
{
attackwait = 0;
}
if (Input.GetMouseButtonDown(0))
{
anim.SetTrigger("Attack");
trigger.enabled = true;
attack = true;
attackwait = 1; //wait 1 sec after attack
}
}
else
{
attackwait = attackwait - (1 * Time.deltaTime);
}
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("Trigger");
if (other.CompareTag("Rat") && attack == true)
{
other.gameObject.GetComponent<Health>().health = other.gameObject.GetComponent<Health>().health - 5;
Debug.Log("I did damage");
}
}
}