Simple follow script issue

Hello,

I’ve been trying this script I’ve only slightly modified for my use. I just want my object to follow my player, and stop when in range. Now it all works fine when I don’t have a Rigidbody on my following object. It stops fine but the object slowly floats and transforms to what seems to be the middle of my player character.

To counteract this I added a rigidbody, it jitters along the floor (As I imagine because it’s trying to float whilst the gravity from the ridigbody is trying to pull it down) When it stops, it’s very jittery.

I’ve tried to disable the rigidbody whilst not moving, but still has an issue.

Could someone offer any guidance on what I could try? Thanks!

var target : Transform;

var rotationSpeed = 3.0;
var moveSpeed = 3.0;
var maxAttackDistance = 0.0;

var isFree : boolean = true;

private var myPosition : Transform;

function Awake()
{
	myPosition = transform;
}

function Start()
{
	var go = GameObject.FindGameObjectWithTag("Player");
	target = go.transform;
}

function Update()
{
	if(isFree == true)
	{
		PlayerDetected();
	}
	
	else
	{
		animation.Play("Idle");
	}
}

function PlayerDetected()
{
	myPosition.rotation = Quaternion.Slerp(myPosition.rotation, Quaternion.LookRotation(target.position - myPosition.position), rotationSpeed * Time.deltaTime);
	
	if(Vector3.Distance(target.position, myPosition.position) >= maxAttackDistance)
	{
		myPosition.position += transform.forward * moveSpeed * Time.deltaTime;
		animation.Play("Run");
	}
	
	else 
	{
		animation.Play("Idle");
	}
}

On line 39, you are looking at the distance between the target’s position and this object’s position. Then you move toward the target’s position as long as that distance is greater than or equal to 0.0 (see line 5). That is causing your problem.

You do not want to match the target’s position exactly. You want to move to the target’s position less an offset. You have to leave room for size of both the target and the object.

Think of it this way: Pretend both target and object are spheres. You want to move them next to each other. If you get to where Vector3.Distance(target,object) is less than the radius size of the target plus the radius size of the object, the two spheres have collided and are partially inside each other.

So, you need to make sure your maxAttackDistance is set to be large enough to reflect how “thick” the object and the target are. If you will want to add in some extra distance to this if you do not want the object to touch your target at all.

If the object has any issues with the vertical motion after the buffer is in place, you may want to take a look at computing the Distance only in X and Z, then adjusting the Y separately to get the object to be hovering at the correct height. (i.e. If you want the object to float at the target’s head height, not at the target’s center point.)