如果我想在二维平面上从点 A(源)到点 B(目标)进行线性插值,我可以这样做。这里的 Vector2 是一个由 x 和 y float 组成的结构体。
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);
}
这样我就可以使用给定的增量从源到目标进行插值。但是,如果我的目标 vector 不是常数怎么办?假设用户可以通过将鼠标光标指向二维平面来更改目的地。对象应线性插值到目标 vector 。
我可以做这样的事情,但它不是线性插值,而是更像 S 形,这不是我想要的。
delta = 0.05f;
currentVector += Interpolate(currentVector, destination, delta);
最佳答案
既然你说你想保持速度恒定,我假设你想要这个:
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;
}
关于c++ - 如何线性插值到不恒定的目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882209/