Interpolation

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

    As an 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, a simple interpolation is usually described as:

    And often simplified to:

    1. 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 simple formula.

    There are other types of interpolations, which will not be covered here. A recommended read afterwards is the Bezier page.

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

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

    GDScript   C#

    1. private float _t = 0.0f;
    2. public override void _PhysicsProcess(float delta)
    3. {
    4. _t += delta * 0.4f;
    5. Position2D a = GetNode<Position2D>("A");
    6. Position2D b = GetNode<Position2D>("B");
    7. sprite.Position = a.Position.LinearInterpolate(b.Position, _t);
    8. }

    It will produce the following motion:

    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 can be used.

    Here is an example of transforming a monkey from Position1 to Position2:

    ../../_images/interpolation_positions.png

    GDScript   C#

    1. private float _t = 0.0f;
    2. public override void _PhysicsProcess(float delta)
    3. {
    4. _t += delta;
    5. Position3D p1 = GetNode<Position3D>("Position1");
    6. Position3D p2 = GetNode<Position3D>("Position2");
    7. monkey.Transform = p1.Transform.InterpolateWith(p2.Transform, _t);
    8. }

    And again, it will produce the following motion:

    Interpolation can be used to smooth movement, rotation, etc. Here is an example of a circle following the mouse using smoothed motion:

    GDScript   C#

    1. private const float FollowSpeed = 4.0f;
    2. public override void _PhysicsProcess(float delta)
    3. {
    4. Vector2 mousePos = GetLocalMousePosition();
    5. Sprite sprite = GetNode<Sprite>("Sprite");
    6. }

    Here is how it looks:

    ../../_images/interpolation_follow.gif