- Home /
Enemy AI Range Detection
So far I gave my enemy a charcater controller, and it follows me everywhere I go, but I want to make it so that if Im within a certain distance it`ll follow me. Heres my code
var target : Transform; //the player
var speed : float = 10; // the speed
var controller:CharacterController;
function Start(){
controller = gameObject.GetComponent(CharacterController);
}
function Update(){
transform.LookAt(target); // the NPC looks at the player
// Here you access the Character Controller component and move your NPC with SimpleMove() giving the speed and the direction(forward).
//As the NPC is looking at you, forward is in your direction.
controller.SimpleMove(speed*transform.forward);
}
}
Answer by cdrandin · Aug 06, 2013 at 04:31 AM
var target : Transform; //the player
var speed : float = 10; // the speed
var controller:CharacterController;
var aiDetectinRange : float 6;
function Start(){
controller = gameObject.GetComponent(CharacterController);
}
function Update(){
transform.LookAt(target); // the NPC looks at the player
// Here you access the Character Controller component and move your NPC with SimpleMove() giving the speed and the direction(forward).
//As the NPC is looking at you, forward is in your direction.
// distance between the current object and the player, if within the distance then move
if( Vect3.Distance(target.transorm.position,transform.position) < aiDetectionRange) )
controller.SimpleMove(speed*transform.forward);
}
}
Answer by emek12 · Aug 06, 2013 at 05:25 AM
This didnt work, the enemy stays in one spot, even when Im right in front of its face
print out the display and see what values you are getting. You want the distance between both player and object. So, check out the docs for how to use it
Answer by Jtbentley_v2 · Aug 06, 2013 at 08:29 AM
aiDetectinRange is spelled wrong. You check against aiDetectionRange, which if you aren't using #pragma strict in the header of the script will dynamically be declared..
I also thought it was Vector3.Distance(a,b)? If Vect3.Distance works, cool.
haha you are right. yeah sorry. Should have double check what I write.
Your answer
Follow this Question
Related Questions
FPS RIGIDBODY PROBLEM 1 Answer
zombie ai script 1 Answer
Spawner + AI control 2 Answers
How to start making a android Game 1 Answer
Deal damage on collision 2 Answers