Stay Back!

How would I modify this script so that if the enemy gets about 1 metre close to the player it stops?

var target : Transform; 

var moveSpeed = 3;

var rotationSpeed = 3;

var myTransform : Transform;

function Awake()

{

myTransform = transform; 

}

function Start()

{

 target = GameObject.FindWithTag("Player").transform; 

}

function Update () {

var lookDir = target.position - myTransform.position;

lookDir.y = 0;

myTransform.rotation = Quaternion.Slerp(myTransform.rotation,

Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime);

myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

}

Please when posting code highlight it and press the “101010” button and it will format it nicely like my code is:

var target : Transform; //Player goes here, the enemy will "chase" and measure distance using this object.
var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform; //Cache our transform to avoid unnecessary calculation 

function Awake(){
    myTransform = transform; //Store our transform
}

function Start(){   
    target = GameObject.FindWithTag("Player").transform; //Acquire our target
}

function Update () {
//Measuring distance
var dist = Vector3.Distance(target.position, myTransform.position);
    //Doing some fancy stuff.
    var lookDir = target.position - myTransform.position;

    lookDir.y = 0;

    myTransform.rotation = Quaternion.Slerp(myTransform.rotation,

    Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime);
    //Checking if the player is more than 1 meter away if so -> don't move at all.
    if(dist > 1){
        myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    }
}

You use [Vector3.Distance][1] to check if the enemy is more than 1 meter away.

Be aware that Vector3.Distance is quiet expensive when called every frame on several objects.
[1]: http://unity3d.com/support/documentation/ScriptReference/Vector3.Distance.html

http://unity3d.com/support/documentation/ScriptReference/Vector3.Distance.html