I set up a scene where a Bear is trying to seek a Raccoon and then chase after it. I created a cone for the bear’s ‘eyes’ and whenever it finds any object with the tag “Prey” it will chase after it.
For some reason when I start the scene the Bear automatically detects the Raccoon and runs after it even if the ray-cast is clearly not colliding. What am I doing wrong?
using UnityEngine;
using System.Collections;
public class Animal : MonoBehaviour {
public bool alive = true;
void OnTriggerEnter(Collider other)
{
if(other.gameObject.name == "Eyes")
{
other.transform.parent.GetComponent<PredatorAI>().checkSight();
}
}
}
In a separate PredatorAI class:
public void checkSight()
{
if(alive)
{
RaycastHit rayHit;
if(Physics.Linecast(eyes.position, prey.transform.position, out rayHit))
{
Debug.Log ("hit "+rayHit.collider.gameObject.tag);
if(rayHit.collider.gameObject.tag == "Prey")
{
if(state != "kill")
{
state = "chase";
Debug.Log ("PredatorAI: " + state);
nav.speed = 3.5f;
anim.speed = 3.5f;
}
}
}
}
}
Imgur Link to what is happening with the console messages:
Only the raccoon has the tag has “Prey” and from my debug message it looks like the raycast instantly hits it and runs the chase state where it moves the Bear towards the Raccoon. I’ve been searching for hours to no luck.
I also checked by using Debug.Log ("hit "+rayHit.collider.gameObject.name);
and it returns the Raccoon_03
. I also made the eyes object ignore Raycasting.