Smoothly follow object within a certain distance

I’ve had success getting an object to follow another object using Vector.SmoothDamp, however this only seems to allow following within a certain timeframe. What I’m looking to do is have smooth following with a maximum distance; when the target object reaches a certain speed the follower should not exceed a maximum distance behind it.

My code to achieve naïve following is this:

var target : Transform;

private var velocity = Vector3.zero;
private var offset : Vector3;

function Start() {
	offset = transform.position - target.position;
}

function Update() {
    transform.position = Vector3.SmoothDamp(transform.position, target.TransformPoint(offset), velocity, 0.1);
}

This is just a quick sketch of the solution - there could be issues with it.

Well, first you’ll need a property for this maximum distance (ie 15 units).

Then just put an IF statement in after you get the new transform.position.

So something like…

Vector3 Diff = transform.position - target.position;
if (Diff.magnitude > MaximumDistance)
{
    float mult = MaximumDistance / Diff.magnitude;
    transform.position -= Diff;
    transform.position += Diff * mult;
}

There should be a already made script in Unity3D. Look in standard Assets