Reputation: 49
I have a Vector2 Lerp statement:
Vector2.Lerp(spawnPos, target, position);
The position
variable is a number between 0 and 1, and for all intents and purposes, it increments over time. Think of the way I'm tracking position
as a "playhead," like in music or animation, where a cursor moves from left to right as the playback continues.
I want the object to continue moving after it reaches its target, at the same EXACT speed, just infinitely in a direction. I've tried to change the target to the direction multiplied by the distance between the spawn point, but I still can't figure out how to get the correct speed.
Upvotes: 1
Views: 1583
Reputation: 422
A slightly easier answer for you: Instead of using Vector2.Lerp
and calculating everything, just use Vector2.LerpUnclamped and throw in any value of t
you want!
Upvotes: 1
Reputation: 49
Thanks to Llama's comment, I was able to calculate the speed of a Lerp.
First, record the start and end time of the interpolation, and whether or not the interpolation has completed (position >= 1
). Then, if it hasn't finished, lerp as normal. If it HAS finished, note the end time, calculate the speed and direction in which to move, and increment Transform.position
by that value.
bool finished = false;
// Since I'm using AudioSettings.dspTime, I need to use double.
// Most forms of telling time in Unity will use float
double startTime;
double endTime;
void Start()
{
// This is what I am using for my game,
// but you can use any way of telling time that Unity/C# provides.
startTime = AudioSettings.dspTime;
}
void Update()
{
if(!finished)
{
// interpolate
transform.position = Vector2.Lerp(spawnPos, targetPos, position);
if(position >= 1)
{
// Record our end time
endTime = AudioSettings.dspTime;
finished = true
}
} else {
// How long it took to lerp
double lerpTime = endTime - startTime;
// How far we lerped
float distance = Vector2.Distance(spawnPos, targetPos);
// The speed to further move
float speed = distance / (float)lerpTime;
// The direction in which to move
Vector2 direction = (targetPos - spawnPos).normalized;
// Continue moving
transform.position += (Vector3)direction * speed * Time.deltaTime;
}
}
Upvotes: 1