插值

插值是图形编程中的一个非常基本的操作。作为一个图形开发人员,熟悉它是很好的,这样可以扩大你的视野。

基本思想是要从A值转换为B值 t ,表示介于两者之间的状态。

例如,如果 t 为0,则状态为A。如果 t 是1,则状态为b。介于两者之间的任何值都是 插值 .

在两个实数(浮点数)之间,一个简单的插值通常描述为:

interpolation = A * (1 - t) + B * t

通常简化为:

interpolation = A + (B - A) * t

完全一样。

这种类型的插值的名称,它将一个值转换为另一个值。 恒速“线性” . 所以,当你听说 线性插值 ,你知道他们指的是这个简单的公式。

还有其他类型的插值,这里不介绍。建议事后阅读 Bezier 页。

矢量插值

矢量类型 (Vector2Vector3 )也可以插入,它们带有方便的函数 Vector2.linear_interpolate()Vector3.linear_interpolate() .

对于三次插值,也有 Vector2.cubic_interpolate()Vector3.cubic_interpolate() ,哪个做一个 Bezier 样式插值。

以下是使用插值从A点到B点的简单伪代码:

func _physics_process(delta):
    t += delta * 0.4

    $Sprite.position = $A.position.linear_interpolate($B.position, t)

它将产生以下运动:

../../_images/interpolation_vector.gif

变换插值

也可以对整个变换进行内插(确保它们具有统一比例,或者至少具有相同的非均匀比例)。为此,函数 Transform.interpolate_with() 可以使用。

下面是一个将猴子从位置1转换为位置2的示例:

../../_images/interpolation_positions.png

使用以下伪代码:

var t = 0.0

func _physics_process(delta):
    t += delta

    $Monkey.transform = $Position1.transform.interpolate_with($Position2.transform, t)

再次,它将产生以下运动:

../../_images/interpolation_monkey.gif

平滑运动

插值可用于平滑移动、旋转等。下面是使用平滑运动跟随鼠标的圆示例:

const FOLLOW_SPEED = 4.0

func _physics_process(delta):
    var mouse_pos = get_local_mouse_position()

    $Sprite.position = $Sprite.position.linear_interpolate(mouse_pos, delta * FOLLOW_SPEED)

这是它的样子:

../../_images/interpolation_follow.gif

这对于平滑相机移动、跟随你的盟友(确保他们保持在一定范围内)以及许多其他常见的游戏模式非常有用。