AI following player script

I found this script:

  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 () {
    myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
     
    Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    }

And now I wanna create animations when AI follows player, like walking animation when he is walking and idle animation when he is idle, that means that the AI must stop at some distance when he is close to player, I’d like so I can set the distance, thanks in advance! :slight_smile:

You can check the distance like so
var dist = Vector3.Distance(target.position, myTransform.position);

Thanks, but how to set the distance now? I can only check it.

Not sure what you mean by “set the distance”. The distance cannot be set, it is dependant on the positions of the objects. I assume you mean you want to set the “minimum distance” where the ai should stop moving towards the player? But that should be obvious, just create a public var, set it in inspector, and only run the code you currently have in the update when the current distance is bigger than the minimum.

Ermmm, well, I’m not really the programmer, that’s only thing I’m missing, so I’d like you to finish my code, thanks. ^^
I tried this: (won’t work)

 var target : Transform;
        var moveSpeed = 3;
        var rotationSpeed = 3;
        var myTransform : Transform;
        public var dist = Vector3.Distance(target.position, myTransform.position); 
        
        function Awake(){
        myTransform = transform;
        }
         
        function Start(){
        target = GameObject.FindWithTag("Player").transform;
        }
         
        function Update () {
        myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
         
        Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
         
        myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
        Vector3.Distance(target.position, myTransform.position);
        }

Well, let’s try to make you a programmer. :slight_smile:

You need to CHECK the result of the Vector3.Distance, and then, if it’s less/greater than a number, do/ don’t do something. See if you can figure it out from there. :slight_smile: