- Home /
how could i make the enemy follow me and stop with the distance to me
My basic following script is look like this :
#pragma strict
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
Now i want to delete this object when i am out of he visual range . (sorry for my bad english :D )
Answer by fafase · Aug 27, 2012 at 11:45 AM
var target:GameObject;
if(Vector3.Distance(transform.position, target.transform.position)>range)
Destroy(target);
Now you might want to simply deactivate the rendering so that it saves resources on the GPU but your guy is still there:
if(Vector3.Distance(transform.position, target.position)>range)
target.renderer.enabled =false;
This way the guy is still out there and if you were to get back closer , hop, he is here. If he has a wandering script then he keeps on walking invisible.
Finally, if you want to deactivate the object so that when out of reach it does not do anything.
if(Vector3.Distance(transform.position, target.position)>range)
target.active =false;
Your answer

Follow this Question
Related Questions
Enemy AI help. 0 Answers
Enemy Attack Animation 1 Answer
How does one write an AI Script for a 3rd person shooter? 0 Answers
Help me with the A* pathfinding. 0 Answers
Can unity3d combined with Artificial Intelligent or Soft Computing? 3 Answers