- Home /
AI line/field of sight with Raycast
I am making a game for a uni project but I got stuck with the Enemy AI. What I am trying to do is make the enemy chase the player if the player is in the line of sight (not hiding behind a wall). I`ve tried a few ways to do it but so far the results are either that the enemy chase the player all the time or does not chase it at all. Before activating the raycast the enemy always looks at the player.
Bellow are the different ways I tried to make it work.
1.The layer mask is set to be the layer where only the player is
if (!Physics.Raycast(transform.position, targetDir, out isPlayer, Mathf.Infinity, layerMask))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
2.
if (Physics.Raycast(transform.position, targetDir, out isPlayer, Mathf.Infinity, layerMask))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
3.
if (Physics.Raycast(transform.position,targetDir,out isPlayer,Mathf.Infinity))
{
if(isPlayer.transform == player)
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
do{ //$$anonymous$$ake the enemy run around in circle (or whatever) in here Debug.DrawRay(transform.position, (Vector3.forward), Color.green);
}While (!Physics.Raycast(transform.position, (Vector3.forward), out (raycastHit), sightRange, Player$$anonymous$$ask))
Debugging the ray might help, I think your problem lies with the direction of the raycast.
I would also suggest triple checking the stuff in your editor.
And finally, are you getting any errors, and are you using the Nav$$anonymous$$esh agent component.
I managed to fix it the problem was at what the raycast is hitting. For some reason it wasn't taking the first thing it hits so I had to create an array of RaycastHit and take the first element of it and then check what the tag is.
Your answer
Follow this Question
Related Questions
How can I get a character to patrol and follow terrain? 1 Answer
Raycast does not go in the right direction 1 Answer
[C#] Raycasts and Object Tags 1 Answer
Raycast & AI problem. 1 Answer