🧮 Lerp & Math Utils

What are they?

The engine includes a set of mathematical and interpolation (Lerp) functions extremely useful for movement, animation, and position calculations in your games.

📖 Available Functions

lerp(a, b, t)

Linear interpolation between a and b, where t goes from 0 to 1.

const x = lerp(0, 100, 0.5); // returns 50

lerpSmooth(current, target, speed, dt)

Smooth interpolation based on delta time. Perfect for camera movements or objects that must follow another with inertia.

obj.x = lerpSmooth(obj.x, player.x, 5, dt);

lerpLoop(a, b, speed, time)

Ping-pong oscillating interpolation using Math.sin.

const alpha = lerpLoop(0, 1, 2, performance.now()/1000);

lerpPingPong(a, b, speed, timer)

Similar to lerpLoop but based on an internal counter. Great for repeating movements.

obj.y = lerpPingPong(100, 200, 3, obj.timer);

clamp(value, min, max)

Restricts a value between a minimum and a maximum.

const hp = clamp(player.hp, 0, 100);

randomRange(min, max)

Returns a random number between min and max.

const speed = randomRange(50, 200);

class Vector2

Utility class for 2D vector operations.

const v1 = new Vector2(10, 20);
const v2 = new Vector2(30, 40);
const dir = v2.sub(v1).normalized();

✅ Practical Example

// Smoothly follow the player with the camera
offsetX = lerpSmooth(offsetX, -player.x + 320, 5, dt);
offsetY = lerpSmooth(offsetY, -player.y + 240, 5, dt);

// Oscillate an object's opacity
obj.opacity = lerpLoop(0.5, 1, 2, performance.now()/1000);

// Move an object toward another
const dir = new Vector2(player.x - obj.x, player.y - obj.y).normalized();
obj.x += dir.x * 100 * dt;
obj.y += dir.y * 100 * dt;

📌 Notes

- Always use dt for smooth, time-dependent movements.
- lerpSmooth is ideal for cameras and transitions.
- lerpLoop and lerpPingPong are perfect for cyclic animations (lights, platforms, enemies).
- Vector2 greatly simplifies direction and distance calculations.