Reputation: 452
If I want to linearly interpolate from point A (source) to point B (destination) on a 2d plane I could do it like this. Vector2 here is a struct consisting of x and y floats.
Vector2 Interpolate(Vector2 source, Vector2 destination, float delta) {
return source+(destination-source)*delta;
}
void OnEachUpdate() {
delta += 0.05f;
delta = max(delta, 1.0f);
currentVector = Interpolate(source, destination, delta);
}
This way I can interpolate from source to destination with a given delta. However what if I have destination vector that is not constant? Say the user can change the destination by pointing a mouse cursor on a 2d plane. An object should linearly interpolate to the destination vector.
I could do something like this but it's not a linear interpolation, but more like sigmoidal, which is not what I want.
delta = 0.05f;
currentVector += Interpolate(currentVector, destination, delta);
Upvotes: 1
Views: 410
Reputation: 96166
Since you said you want to keep the speed constant, I assume you want this:
float speed = whatever;
float delta_x = target_x - current_x;
float delta_y = target_y - current_y;
float dist_sqr = delta_x*delta_x + delta_y*delta_y;
if (dist_sqr <= speed*speed)
{
// The destination is reached.
current_x = target_x;
current_y = target_y;
}
else
{
float dist = std::sqrt(dist_sqr);
current_x += delta_x / dist * speed;
current_y += delta_y / dist * speed;
}
Upvotes: 1