Skip to content

Commit

Permalink
Add the math3d.move_towards function
Browse files Browse the repository at this point in the history
  • Loading branch information
aglitchman committed Apr 20, 2022
1 parent 99e2f70 commit 9e3115f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ The table briefly describes the included helper math functions. The source code
| `math3d.lerp(t, a, b, [dt])` | Linearly interpolates between `a` and `b` by `t`. The parameter `t` is clamped to the range `[0, 1]`. | `Mathf.Lerp` |
| `math3d.lerp_angle(t, a, b, [dt])` | Same as `vmath.lerp` but makes sure the values interpolate correctly when they wrap around 360 degrees. | `Mathf.LerpAngle` |
| `math3d.limited_lerp(t, a, b, max_step)` | Same as `vmath.lerp` but `max_step` limits the increment of value. | - |
| `math3d.move_towards(a, b, max_delta)` | Moves the `a` value towards `b`. | `Mathf.MoveTowards` |
| `math3d.ping_pong(t, length)` | Pingpongs the value t, so that it is never larger than length and never smaller than 0. | `Mathf.PingPong` |
| `math3d.repeat_(t, length)` | Loops the value t, so that it is never larger than length and never smaller than 0. | `Mathf.Repeat` |
| `math3d.sign(x)` | Returns the sign of x. | `Mathf.Sign` |
Expand Down
14 changes: 13 additions & 1 deletion scene3d/helpers/math3d.lua
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ function M.lerp_angle(t, a, b, dt)
end

--- Calculates the lerp parameter between of two values.
-- @param t Value between start and end.
-- @param a Start value.
-- @param b End value.
-- @param t Value between start and end.
-- @return A percentage of value between start and end.
function M.inverse_lerp(t, a, b)
if a ~= b then
Expand All @@ -203,6 +203,18 @@ function M.inverse_lerp(t, a, b)
end
end

--- Moves the `a` value towards `b`.
-- @param a Current value.
-- @param b Target value.
-- @param max_delta A maximum change that should be applied to the value.
-- @return An interpolated value.
function M.move_towards(a, b, max_delta)
if math.abs(b - a) <= max_delta then
return b
end
return a + M.sign(b - a) * max_delta
end

--- Pingpongs the value t, so that it is never larger than length and never smaller than 0.
function M.ping_pong(t, length)
t = M.repeat_(t, length * 2)
Expand Down

0 comments on commit 9e3115f

Please sign in to comment.