Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Интерполяция

Интерполяция — одна из самых базовых операций в программировании графики. Будет неплохо с ней ознакомиться, дабы расширить Ваши горизонты как разработчика графики.

The basic idea is that you want to transition from A to B. A value t, represents the states in-between.

For example, if t is 0, then the state is A. If t is 1, then the state is B. Anything in-between is an interpolation.

Between two real (floating-point) numbers, an interpolation can be described as:

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

И часто сокращается до:

interpolation = A + (B - A) * t

The name of this type of interpolation, which transforms a value into another at constant speed is "linear". So, when you hear about Linear Interpolation, you know they are referring to this formula.

Существуют другие типы интерполяций, о которых мы не будем здесь говорить. Чтобы прочесть о них, Вам рекомендуется проследовать на страницу Bezier.

Векторная интерполяция

Vector types (Vector2 and Vector3) can also be interpolated, they come with handy functions to do it Vector2.lerp() and Vector3.lerp().

For cubic interpolation, there are also Vector2.cubic_interpolate() and Vector3.cubic_interpolate(), which do a Bezier style interpolation.

Here is example pseudo-code for going from point A to B using interpolation:

var t = 0.0

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

    $Sprite2D.position = $A.position.lerp($B.position, t)

It will produce the following motion:

../../_images/interpolation_vector.gif

Интерполяция трансформаций

It is also possible to interpolate whole transforms (make sure they have either uniform scale or, at least, the same non-uniform scale). For this, the function Transform3D.interpolate_with() can be used.

Вот пример трансформирования обезьяны с первой позиции (Position1) на вторую (Position2):

../../_images/interpolation_positions.png

Using the following pseudocode:

var t = 0.0

func _physics_process(delta):
    t += delta

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

And again, it will produce the following motion:

../../_images/interpolation_monkey.gif

Smoothing motion

Интерполяция может быть использована для сглаживания движений, поворотов, и т. п. Вот пример круга, следующего за мышкой с использованием плавного движения:

const FOLLOW_SPEED = 4.0

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

    $Sprite2D.position = $Sprite2D.position.lerp(mouse_pos, delta * FOLLOW_SPEED)

Here is how it looks:

../../_images/interpolation_follow.gif

Это полезно для плавного движения камеры, союзников, следующих за вами (гарантируя, что они находятся в определённом радиусе) и для многих других распространённых игровых паттернов.