- Home /
Object move on RaycastHit
So I'm trying to make my Enemy AI flee if a Raycast from the player hits the Enemy.
This is all within a working State Machine so lets get past that.
I use a NavMesh for the enemy movement if you're wondering.
if (player.GetComponent<Interact>().LookAt())
{
Debug.Log("Player See's Me!");
}
This is what is inside my "flee state".
public bool LookAt()
{
Debug.DrawRay(transform.position, transform.forward * 100, Color.yellow); //Debug raycast
if (Physics.Raycast(transform.position, transform.forward, out hit, 100)) //Raycast)
{
hit.transform.CompareTag("Enemy");
return true;
}
return false;
}
This is inside a script that is attached to my Player Camera.
LookAt() is called within Update().
I have never tried anything like this so this is beyond my basic understanding.
This gives me a NullReferenceException within Unity. So it obviously does not work.
Does anyone have a better suggestion for this? I'm not too worried about making the NavMeshAgent move I just want this DebugLog to appear. :P
I'm now of the belief that I have approached this all wrong. I feel that I should have my enemy use a Spherecast ins$$anonymous$$d. I will return if this results in nothing.
Answer by BMRX · May 14, 2015 at 06:22 PM
ShpereCast was not the answer,
public override void Act(Transform player, Transform npc)
{
RaycastHit hit;
Collider[] colli = Physics.OverlapSphere(npc.transform.position, 50f);
foreach (Collider col in colli)
{
if (Physics.Raycast(npc.transform.position, (col.transform.position - npc.transform.position), out hit, 50f))
{
if (hit.transform.CompareTag("Player"))//player detector
{
Debug.Log("Player Spotted");
}
}
}
}
This was.
If someone posts a better answer than this I'm more than willing to give the green to them. :D
EDIT/ Didn't think about it but, I need this only to work if the AI has no colliders in between it and the player. Essentially I want it to look for cover from the Players fire. This could however work fine for some sort of panic state. Just have the agent in your navmesh run to a random direction. If you use:
Vector3 position = new Vector3(Random.Range(-40.0F, 264.0F), Random.Range(6.0F, 10.0F), Random.Range(-200.0F, 95.0F));
agent.SetDestination(position);
The agent/AI stutters around the map like its dancing or something. I'm certain if you used a better method to set the destination it would move more smoothly.
Your answer
![](https://koobas.hobune.stream/wayback/20220613195607im_/https://answers.unity.com/themes/thub/images/avi.jpg)