如何线性插值到不恒定的目的地
How to linearly interpolate to destination that is not constant
如果我想在二维平面上从点 A(源)到点 B(目标)进行线性插值,我可以这样做。这里的 Vector2 是一个由 x 和 y 浮点数组成的结构。
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);
}
这样我就可以使用给定的增量从源到目标进行插值。但是,如果我的目标向量不是常数怎么办?假设用户可以通过将鼠标光标指向二维平面来更改目的地。对象应线性插值到目标向量。
我可以做这样的事情,但它不是线性插值,而是更像 sigmoidal,这不是我想要的。
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;
}
如果我想在二维平面上从点 A(源)到点 B(目标)进行线性插值,我可以这样做。这里的 Vector2 是一个由 x 和 y 浮点数组成的结构。
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);
}
这样我就可以使用给定的增量从源到目标进行插值。但是,如果我的目标向量不是常数怎么办?假设用户可以通过将鼠标光标指向二维平面来更改目的地。对象应线性插值到目标向量。
我可以做这样的事情,但它不是线性插值,而是更像 sigmoidal,这不是我想要的。
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;
}