Interpolation
Interpolation is a very basic operation in graphics programming. It’s good to become familiar with it in order to expand your horizons as a graphics developer.
t, represents the states in-between.
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:
interpolation = A * (1 - t) + B * t
And often simplified to:
interpolation = A + (B - A) * t
constant speed is “linear”. So, when you hear about Linear Interpolation, you know they are referring to this simple formula. Bezier page.
Vector interpolation
Vector2 and Vector3) can also be interpolated, they come with handy functions to do it Vector2.linear_interpolate() and Vector3.linear_interpolate(). Vector2.cubic_interpolate() and Vector3.cubic_interpolate(), which do a Bezier style interpolation. Here is simple pseudo-code for going from point A to B using interpolation: GDScript C#
var t = 0.0func _physics_process(delta): t += delta * 0.4 $Sprite.position = $A.position.linear_interpolate($B.position, t)
private float _t = 0.0f;public override void _PhysicsProcess(float delta){ _t += delta * 0.4f; Position2D a = GetNode<Position2D>("A"); Position2D b = GetNode<Position2D>("B"); Sprite sprite = GetNode<Sprite>("Sprite"); sprite.Position = a.Position.LinearInterpolate(b.Position, _t);}
It will produce the following motion:
Transform interpolation
Transform.interpolate_with() can be used. Here is an example of transforming a monkey from Position1 to Position2: Using the following pseudocode: GDScript C#
var t = 0.0func _physics_process(delta): t += delta $Monkey.transform = $Position1.transform.interpolate_with($Position2.transform, t)
private float _t = 0.0f;public override void _PhysicsProcess(float delta){ _t += delta; Position3D p1 = GetNode<Position3D>("Position1"); Position3D p2 = GetNode<Position3D>("Position2"); CSGMesh monkey = GetNode<CSGMesh>("Monkey"); monkey.Transform = p1.Transform.InterpolateWith(p2.Transform, _t);}
And again, it will produce the following motion:
Smoothing 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#
const FOLLOW_SPEED = 4.0func _physics_process(delta): var mouse_pos = get_local_mouse_position() $Sprite.position = $Sprite.position.linear_interpolate(mouse_pos, delta * FOLLOW_SPEED)
private const float FollowSpeed = 4.0f;public override void _PhysicsProcess(float delta){ Vector2 mousePos = GetLocalMousePosition(); Sprite sprite = GetNode<Sprite>("Sprite"); sprite.Position = sprite.Position.LinearInterpolate(mousePos, delta * FollowSpeed);}
Here is how it looks: This useful for smoothing camera movement, allies following you (ensuring they stay within a certain range), and many other common game patterns.
