# How to Lerp between to Vector3 positions (C#)

So I have 2 variables that are holding Vector3's (one is the previous position, and the other is the new position), and I want to use Lerp to smoothly move the object from the previous position to the new position. I'm having trouble getting this to work correctly, and I'm pretty sure I'm just not writing the syntax correctly. lastStates is a Dictionary holding the position for this particular user (not sure if that matters in this case since it is defined as a Vector3).

``````Vector3 pos = new Vector3(x, y, z);
GameObject.Find("remote_" + userId).transform.position = Vector3.Lerp(lastStates[userId], pos, t);

``````

You have to move it over time, such as in a coroutine like this (not C#, but the idea is the same, you just have to adapt the syntax).

I just wrote this (untested as yet!) but you might find it useful:

``````public static Vector3 InterpolateStepOverTime(Vector3 Current, Vector3 Target, float DeltaTime, float InterpSpeed)
{
Vector3 delta = Target - Current;
if ( delta.sqrMagnitude < Mathf.Epsilon)//distance to our target is zero. Already at our target.
{
return Target;
}

Vector3 vectorDir = Vector3.Normalize(delta);
Vector3 stepSize = DeltaTime * InterpSpeed * vectorDir;//How far to travel this frame.
Vector3 finalPos = Current + stepSize;

if (Vector3.Dot(finalPos - Current, (Target - Current).normalized) / (Target - Current).magnitude >= 1.0f)//See if the final position is proportionally further than the end position. If it is, clamp us to the end point so that we don't overshoot and "vibrate" back and forth over the target position.
{
finalPos = Target;
}
return finalPos;
}

``````

Typical use case: in your Update function:

``````CurrentPos = InterpolateStepOverTime(CurrentPos, TargetPos, Time.deltaTime, 2.0f);

``````

This will cause your CurrentPos to step toward its target at a rate of 2 u/s.

As I say, this is untested, but it's a useful thing to have.