AI Following too closely...

Yo, the coding for my enemy to follow me around is making him come a bit too close, meaning he wont stop until he’s inside me. So how can I implement a code to make him stop a bit back from the character? (Enough so I can let him try to hit me with a sword and visa/versa, should be fine as I can change it up later as long as I know the code). I’m really new to unity so some example code would be greatly appreciated :slight_smile:

using UnityEngine;
using System.Collections;

public class AIFollow : MonoBehaviour 
{
	public Transform target;
	public int moveSpeed = 2;
	public int rotationSpeed = 1;
	public Transform myTransform;
	
	void Awake ()
	{
		myTransform = transform;
	}
	
	void Start () 
	{
		target = GameObject.FindWithTag ("Player").transform;
	}
	
	void Update () 
	{
		myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * moveSpeed * Time.deltaTime);
		myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
	}
}

check the distance from target and update player position.

this will help you : Unity - Scripting API: Vector3.Distance

float minimumDistance = 2.0f;
   if( Vector3.Distance(target.position, transform.position) > minimumDistance)
   {
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime; // update enemy position
   }

Add another float to tell it how close you want it to get like:

public float attackRange = 3f;

Then in your update loop you can check the distance and if he’s close enough stop.

if (Vector3.Distance(myTransform.position, target.position) > attackRange)
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

And just for good measure, using sqrMagnitude is more efficient that Vector3.Distance

if ((myTransform.position - target.position).sqrMagnitude > attackRange * attackRange)
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;