Skip to content

Instantly share code, notes, and snippets.

@aglitchman
Created November 15, 2025 10:58
Show Gist options
  • Select an option

  • Save aglitchman/89669be6717618b2fe7410b1b1245bd3 to your computer and use it in GitHub Desktop.

Select an option

Save aglitchman/89669be6717618b2fe7410b1b1245bd3 to your computer and use it in GitHub Desktop.
Smooth damping for Defold
local M = {}
--- Gradually changes a value towards a desired goal over time.
-- This function provides smooth damping interpolation, useful for creating smooth camera movements,
-- UI animations, or any value that needs to smoothly approach a target.
-- Based on Game Programming Gems 4, pp. 98-101.
-- @param a number Current value
-- @param b number Target value
-- @param cur_velocity number Current velocity
-- @param smooth_time number Approximate time it will take to reach the target
-- @param max_speed number Optionally allows you to clamp the maximum speed (optional)
-- @param dt number Delta time
-- @return number The new smoothed value
-- @return number The new velocity
function M.smooth_damp(a, b, cur_velocity, smooth_time, max_speed, dt)
smooth_time = math.max(0.0001, smooth_time)
local omega = 2 / smooth_time
local x = omega * dt
local exp = 1 / (1 + x + 0.48 * x * x + 0.235 * x * x * x)
local change = a - b
local initial_b = b
if max_speed then
local max_change = max_speed * smooth_time
change = vmath.clamp(change, -max_change, max_change)
end
b = a - change
local temp = (cur_velocity + omega * change) * dt
cur_velocity = (cur_velocity - omega * temp) * exp
local result = b + (change + temp) * exp
if (initial_b - a > 0) == (result > initial_b) then
result = initial_b
cur_velocity = (result - initial_b) / dt
end
return result, cur_velocity
end
-- Example:
-- Requires:
-- > dt = <float> -- delta time
-- > camera_object_id = hash("/camera_object")
-- > camera_velocity = vmath.vector3()
-- > target_pos = vmath.vector3()
--
-- local smooth_time = 0.15
-- local current_pos = go.get_position(camera_object_id)
-- current_pos.x, camera_velocity.x = M.smooth_damp(current_pos.x, target_pos.x, camera_velocity.x, smooth_time, nil, dt)
-- current_pos.y, camera_velocity.y = M.smooth_damp(current_pos.y, target_pos.y, camera_velocity.y, smooth_time, nil, dt)
-- current_pos.z, camera_velocity.z = M.smooth_damp(current_pos.z, target_pos.z, camera_velocity.z, smooth_time, nil, dt)
-- go.set_position(current_pos, camera_object_id)
--
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment