tags: physics title: Fixed timestep interpolation brief: This example shows how to smooth physics motion in fixed update mode by interpolating a visual sprite while keeping the physics body fixed-step. author: Defold Foundation scripts: interpolation.script
This example demonstrates two rendering paths while physics runs at a fixed frequency:
Not interpolated: visual sprite follows the dynamic body directly (visually looks like it has a stepped motion).Interpolated: visual sprite is interpolated between fixed physics states (smooth motion).The key idea is to separate physics simulation from rendering:
In game.project:
Physics section set Use_Fixed_Timestep enabled and Velocity Threshold to 50 (It is necessary for 2D physics, because velocity threshold is scaled with the scale option, and in the end it should be 1.0 internally in Box2D, so if Scale is set to 0.02, the velocity threshold should be 50 = 1.0 / 0.02). Gravity is set arbitraly for this example to -500.Engine section set Fixed Update Frequency to a low value, e.g. 20, so the difference is easy to see.The setup consists of 5 game objects:
walls
: Static borders and the script host.
/example/interpolation.script.block1
: Game Object for the non-interpolated path for the physics component.
block1_sprite
: Game Object for the non-interpolated path for the visual representation.
Not interpolated).block2
: Game Object for the interpolated path for the physics component.
block2_sprite
: Game Object for the non-interpolated path for the visual representation.
Interpolated)./example/interpolation.script:
block2:
previous = previous fixed physics samplecurrent = current fixed physics samplefixed_update(), shifts values (current data becomes previous data) and samples a new current transform from the objects controlled by the dynamic collision objects.update(), computes render progress inside the current fixed interval:
alpha = render_accumulator / fixed_dtblock1_sprite from raw block1 transform.block2_sprite from interpolated transform (position is interpolated using vmath.lerp(), and rotation is interpolated using vmath.slerp()).At runtime:
block1_sprite appears updated at the fixed frequency.block2_sprite appears updated each frame.