Up to date

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

Інтерполяція

Інтерполяція є самою базовою операцією в графічному програмуванні. Буде добре ознайомитися з нею, щоб розширити свій кругозір розробника графіки.

Основна ідея полягає в тому, що ви хочете перейти від А до В. Значення t, представляє стани між ними.

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.

Є й інші види інтерполяції, які тут не будуть розглядатися. Тому, після цієї статті, рекомендується прочитати сторінку Безьє.

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

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

Для кубічної інтерполяції існують також Vector2.cubic_interpolate() та Vector3.cubic_interpolate(), які виконують інтерполяцію в стилі Безьє.

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)

Він буде виробляти наступний рух:

../../_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.

Ось приклад перетворення мавпочки з Позиції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()

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

Ось як це виглядає:

../../_images/interpolation_follow.gif

Це корисно для згладжування руху камери, союзників, що йдуть за вами (гарантуючи, що вони залишаються в межах певного діапазону), і багатьох інших поширених моделей гри.