- Home /
AI detection script problem
Hi Unity :D
I'm working in a little survival FPS game and at first I'm working on the hardest thing: the AI scripts.This script need to do that when the player is in the field of view of the enemy and if there is not object between Player and enemy, Log says "Can see player" or "cannot see player"(for this moment ^^). For the detection, I've used a script founded on this site:
var playerObject : GameObject; // the player
var fieldOfViewRange : float; // in degrees (I use 68, this gives the enemy a vision of 136 degrees) var minPlayerDetectDistance : float; // the distance the player can come behind the enemy without being deteacted var rayRange : float; // distance the enemy can "see" in front of him private var rayDirection = Vector3.zero;
function Update() { var hit : RaycastHit; rayDirection = playerObject.transform.position - transform.position; var distanceToPlayer = Vector3.Distance(transform.position, playerObject.transform.position);
if(Physics.Raycast (transform.position, rayDirection, hit)){ // If the player is very close behind the enemy and not in view the enemy will detect the player
if((hit.transform.tag == "Player") && (distanceToPlayer <= minPlayerDetectDistance)){
Debug.Log("Caught player sneaking up behind!");
return false;
}
}
if((Vector3.Angle(rayDirection, transform.forward)) < fieldOfViewRange){ // Detect if player is within the field of view
if (Physics.Raycast (transform.position, rayDirection, hit, rayRange)) {
if (hit.transform.tag == "Player") {
Debug.Log("Can see player");
return false;
}
}
}
else
{
Debug.Log("Can not see player");
return false;
}
}
The script works good but I have a problem: when I start the game, Log says "cannot see player", and when I go in the field of view, he says "Can see player". But the problem is that when I go out of the field of view, he always says that he sees player, and he do the same for the proximity sensor. Maybe its very simple to do but I'm beginning in scripting with Unity and its not allways simple ^^. And I have another question : what does "return true" and "return false" I think that its the reason of my problem and I want to know what it is ;D
Thanks a lot and sorry for my bad English (I'm French xD) EDCDragon
Your answer
Follow this Question
Related Questions
How to stop enemy shooting through wall 1 Answer
How to Stop Enemy "Shooting Through A Wall" 1 Answer
enemy raycast to detect player 1 Answer
180 Degree raycast 1 Answer
raycast hit not detecting && Nav mesh agent ai stealth 1 Answer