Skip to content
Engine

Math and Space

MathKit

Interpolation, easing, angles, smoothing, projectile maths, geometry tests, statistics, curves and colour conversion.

PackageShared

Getting it

local MathKit = Engine:GetPackage("MathKit")

Overview

MathKit is a flat library of pure functions: nothing to construct, nothing to clean up. It groups the maths that shows up in almost every game.

local MathKit = Engine:GetPackage("MathKit")

-- Fade a value in with an easing curve
local alpha = MathKit.ease(elapsed / duration, "OutCubic")
frame.BackgroundTransparency = MathKit.lerp(1, 0, alpha)

-- Smoothly follow a moving target every frame
cameraHeight, heightVelocity = MathKit.smoothDamp(cameraHeight, targetHeight, heightVelocity, 0.25, dt)

-- Where will a thrown grenade be after 0.8 seconds?
local position = MathKit.trajectoryPoint(origin, velocity, workspace.Gravity, 0.8)

Note

MathKit.lerp clamps t to 0..1, so it never overshoots. Use lerpUnclamped when you want to extrapolate.

Interpolation

FunctionDescription
lerp(a, b, t)Linear blend from a to b, with t clamped to 0..1.
lerpUnclamped(a, b, t)Same without clamping.
inverseLerp(a, b, value)Where value sits between a and b, clamped to 0..1. 0 when a == b.
map(value, inMin, inMax, outMin, outMax)Re-scale without clamping.
remap(value, fromA, fromB, toA, toB)Re-scale with clamping.
bilerp(a, b, c, d, tx, ty)Blend four corners of a square.
trilerp(c000, ..., c111, tx, ty, tz)Blend eight corners of a cube.
smoothStep(edge0, edge1, x), smootherStep(edge0, edge1, x)S-shaped 0..1 transition between two edges.
normalize(value, min, max), denormalize(value, min, max)To and from the 0..1 range.
percentage(value, total)value / total * 100.

Rounding and ranges

FunctionDescription
clamp01(n), saturate(n)Clamp to 0..1.
clampMagnitude(v, max)A Vector3 no longer than max.
round(n, step?), floorTo(n, step?), ceilTo(n, step?), snap(n, step?)Round to a multiple of step (default 1).
roundHalfEven(n)Banker's rounding.
truncate(n)Drop the fraction towards zero.
wrap(value, min, max)Wrap around a range, like an angle.
bounce(value, min, max)Bounce back and forth inside a range.
repeatValue(t, length), pingPong(t, length)Loop or ping-pong t within 0..length.
sign(n), fract(n)Sign (-1, 0, 1) and fractional part.
nearlyEqual(a, b, epsilon?)Compare with a tolerance.
isNaN(n), isInfinite(n), isFinite(n), sanitize(n, fallback?)Guard against bad numbers. sanitize returns fallback (default 0) for NaN or infinity.

Angles

All angles are in radians unless the name says Deg.

FunctionDescription
wrapAngle(radians), wrapAngleDeg(degrees)Into -pi..pi or -180..180.
deltaAngle(a, b)Shortest signed difference.
angleBetween(a, b)Shortest unsigned difference.
angleLerp(a, b, t)Blend angles the short way round.
angleToVector2(radians), vector2ToAngle(v)Convert between an angle and a direction.

Easing

MathKit.ease(t, style?) applies an easing curve to t in 0..1. Styles: Linear, InSine, OutSine, InOutSine, and the same In/Out/InOut variants of Quad, Cubic, Quart, Quint, Expo, Circ, Back, Elastic and Bounce. Each style is also a function of its own, such as MathKit.easeOutBounce(t).

Motion

FunctionDescription
moveTowards(current, target, maxDelta)Step towards a target without overshooting.
rotateTowards(current, target, maxRadians)Same for angles.
smoothDamp(current, target, velocity, smoothTime, dt, maxSpeed?)Spring-like smoothing. Returns the new value and the new velocity; keep the velocity between frames.
smoothDampAngle(...)Same for angles.

Projectiles

gravity is a positive number such as workspace.Gravity.

FunctionDescription
trajectoryPoint(origin, velocity, gravity, t)Position after t seconds.
trajectoryVelocityAt(velocity, gravity, t)Velocity after t seconds.
projectileTimeToApex(vy, gravity)Seconds until the highest point.
projectileMaxHeight(vy, gravity)Height gained at the apex.
projectileRange(speed, angle, gravity)Horizontal distance on flat ground.

Vectors and geometry

FunctionDescription
reflect(v, normal), refract(v, normal, eta)Bounce or bend a direction off a surface.
project(a, b), projectOnPlane(v, normal)Vector projection.
closestPointOnSegment(p, a, b), closestPointOnLine(p, a, b)Nearest point.
distanceToSegment(p, a, b)Distance from a point to a segment.
closestPointOnPlane(p, planePoint, normal), closestPointOnTriangle(p, a, b, c)Nearest point.
triangleArea(a, b, c), triangleNormal(a, b, c)Triangle properties.
barycentric(p, a, b, c), pointInTriangle(p, a, b, c)Point inside a triangle.
polygonArea(points), pointInPolygon(p, points)2D polygons (Vector2).

Intersections

Ray functions return the distance along dir to the hit, or nil for a miss.

FunctionDescription
rayPlane(origin, dir, planePoint, normal)Ray against a plane.
raySphere(origin, dir, center, radius)Ray against a sphere.
rayBox(origin, dir, cframe, size)Ray against an oriented box.
rayTriangle(origin, dir, a, b, c)Ray against a triangle.
linePlane(a, b, planePoint, normal), lineSphere(a, b, center, radius)Intersection point, or nil.
segmentSphere(a, b, center, radius)Whether a segment touches a sphere.
segmentSegment2D(a, b, c, d)Crossing point of two 2D segments, or nil.
aabbOverlap(minA, maxA, minB, maxB)Axis-aligned boxes.
sphereOverlap(...), circleOverlap2D(...)Spheres and circles.

Curves

FunctionDescription
bezier2(p0, p1, p2, t)Quadratic Bézier.
bezier3(p0, p1, p2, p3, t)Cubic Bézier.
bezierN(points, t)Bézier through any number of control points.
catmullRom(p0, p1, p2, p3, t)Curve through p1 and p2.
hermite(p0, m0, p1, m1, t)Curve with explicit tangents.

For full paths with arc-length and following, see Spline.

Statistics

Variadic functions take numbers as separate arguments: MathKit.average(1, 2, 3). Use table.unpack for an array.

FunctionDescription
sum, average, median, mode, min, max, rangeThe basics.
variance, standardDeviation, rmsSpread.
percentile(data, p)The pth percentile (0-100) of an array.
normalizeDataset(data)Scale an array to 0..1.

Number theory

isEven, isOdd, isPowerOfTwo, nextPowerOfTwo, previousPowerOfTwo, factorial, gcd, lcm, isPrime, fibonacci, combinations(n, r), permutations(n, r), plus bit helpers bitCount, reverseBits, rotateLeft(n, bits) and rotateRight(n, bits).

Colour

Channels are 0..1.

FunctionDescription
rgbToHsv(r, g, b), hsvToRgb(h, s, v)HSV conversion.
rgbToHsl(r, g, b), hslToRgb(h, s, l)HSL conversion.
hexToRgb("#FF8800"), rgbToHex(r, g, b)Hex strings.
colorTemperatureToRgb(kelvin)Colour of light at a temperature (1000 to 40000 K), handy for lighting.
colorLerp(a, b, t)Blend two Color3 values.
lighten(color, amount), darken(color, amount)Adjust brightness.

Configuration

Defaults from DefaultConfiguration/Packages/MathKit7 settings
SettingDefaultWhat it does
DefaultEpsilon1e-6Tolerance approximate comparisons use when no epsilon is passed.
DefaultEaseStyle"Linear"Easing style .ease() uses when none is passed.
DefaultRoundStep1Step .round() snaps to when none is passed.
DefaultFloorStep1Step .floor() snaps to when none is passed.
DefaultCeilStep1Step .ceil() snaps to when none is passed.
DefaultSnapStep1Step .snap() snaps to when none is passed.
DefaultMaxSpeedmath.hugeSpeed cap the motion helpers use when none is passed.