- Home /
Enemy AI Problem
Hello!
I'm making a horror game in which the monster searches for you and if it finds you it starts chasing you. Everything Works fine, the monster is moving from one target to another and when it sees you it chases you. The problem is that when it changes targets it should only change once but it changes many times and after some time it finally goes to one of them. I have done a similar script some months ago and it worked correctly. What's the problem?
Here's the script:
var agent : NavMeshAgent;
var targets : Transform[];
var player : Transform;
var viewDistance : float = 12.5;
var done = true;
var chasing = false;
function Start() {
agent = GetComponent(NavMeshAgent);
}
function Update() {
var shootFrom = Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
var shootTo = Vector3(player.transform.position.x, player.transform.position.y, player.transform.position.z);
var rayDirection = shootTo - shootFrom;
var hit : RaycastHit;
if(Physics.Raycast(shootFrom, rayDirection, hit, viewDistance)) {
if(hit.collider.gameObject.tag == "Player") {
Chase();
chasing = true;
} else {
Search();
chasing = false;
}
} else {
Search();
chasing = false;
}
if(agent.remainingDistance < 0.1 && !chasing) {
Wait();
}
}
function Wait() {
yield WaitForSeconds(3.5);
done = true;
}
function Chase() {
agent.destination = player.position;
agent.speed = 3.75;
}
function Search() {
if(done) {
done = false;
agent.destination = targets[Random.Range(0,targets.length)].position;
agent.speed = 3.5;
}
}
Comment