- Home /
Enemy Ai Field of View
Hey guys,
I managed to get a script working where the enemy will follow the player and catch him. Because I am making a stealth game I am wondering if anyone knows how to give the enemy a field of view? This would enable me to stop the enemy mindlessly following the player until he spots him. And the enemy field of view should be broken by objects so the player can hide behind them.
Cheers for the help!
Here's the code
using UnityEngine; using System.Collections;
public class EnemyAi : MonoBehaviour { public Transform target; public int moveSpeed; public int rotationSpeed; public int maxdistance;
private Transform myTransform;
void Awake(){
myTransform = transform;
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxdistance = 2;
}
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.red);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxdistance){
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
An Easy work around would be to drag out a Sphere and turn off the mes renderer on the sphere. Drag the Sphere on to the enemy and reset the transform of the sphere so that it is on the enemy. Now create a scipt that tells the enemy to LookAt(); the player when the player enters the trigger/collider area of the sphere thats on the enemy.
That' a great idea buddy, so the sphere acts as the trigger, very clever! Will give it a go amigo, cheers again!