The Same Math in Every Engine
Everything in this course exists, ready-made, in every engine and math library. The names differ, a few conventions differ, and a handful of functions do something subtly different from what their name suggests. This lesson is a phrasebook: the same everyday operations written in Unity C#, Unreal C++, Godot GDScript, Three.js and GLM. None of these blocks run on the site; they are real API calls for Unity 6, Unreal Engine 5, Godot 4, Three.js r16x+ and GLM 1.0.
Quick reference
| Operation | Unity | Unreal | Godot | Three.js | GLM |
|---|---|---|---|---|---|
| length | v.magnitude |
V.Size() |
v.length() |
v.length() |
glm::length(v) |
| normalize (safe) | v.normalized |
V.GetSafeNormal() |
v.normalized() |
v.normalize() (in place) |
glm::normalize(v) (NaN on zero!) |
| dot | Vector3.Dot(a, b) |
FVector::DotProduct(A, B) or A | B |
a.dot(b) |
a.dot(b) |
glm::dot(a, b) |
| cross | Vector3.Cross(a, b) |
FVector::CrossProduct(A, B) or A ^ B |
a.cross(b) |
new Vector3().crossVectors(a, b) |
glm::cross(a, b) |
| distance | Vector3.Distance(a, b) |
FVector::Dist(A, B) |
a.distance_to(b) |
a.distanceTo(b) |
glm::distance(a, b) |
| lerp | Vector3.Lerp(a, b, t) (clamped) |
FMath::Lerp(A, B, T) |
a.lerp(b, t) |
a.lerp(b, t) (in place) |
glm::mix(a, b, t) |
| angle between | Vector3.Angle(a, b) (degrees) |
FMath::Acos(FVector::DotProduct(A.GetSafeNormal(), B.GetSafeNormal())) |
a.angle_to(b) (radians) |
a.angleTo(b) (radians) |
glm::angle(a, b) (gtx, needs unit vectors) |
| quaternion from axis-angle | Quaternion.AngleAxis(deg, axis) |
FQuat(Axis, Radians) |
Quaternion(axis, radians) |
new Quaternion().setFromAxisAngle(axis, rad) |
glm::angleAxis(rad, axis) |
| rotate a vector | q * v |
Q.RotateVector(V) |
q * v |
v.applyQuaternion(q) |
q * v |
| slerp | Quaternion.Slerp(a, b, t) |
FQuat::Slerp(A, B, T) |
a.slerp(b, t) |
a.slerp(b, t) (in place) |
glm::slerp(a, b, t) |
| random with seed | Random.InitState(s) |
FRandomStream(Seed) |
RandomNumberGenerator + seed |
MathUtils.seededRandom(s) |
(use <random>) |
Two things in that table catch people out. Three.js mutates in place: a.lerp(b, t) changes a, so write a.clone().lerp(b, t) when you need to keep the original. GLM's normalize of a zero vector is NaN, with no safe variant; check the length first.
Aim at a target: dot, cross, look rotation
The same small task in each engine: is the target in front of me (within a 90° cone), on which side, and turn smoothly toward it at any frame rate.
Unity (C#) is left-handed, Y-up, and an object's forward is +Z (transform.forward):
Vector3 toTarget = target.position - transform.position;
Vector3 dir = toTarget.normalized;
bool inFront = Vector3.Dot(transform.forward, dir) > Mathf.Cos(45f * Mathf.Deg2Rad);
float side = Vector3.Cross(transform.forward, dir).y; // > 0: target is to the RIGHT (left-handed!)
float signedYaw = Vector3.SignedAngle(transform.forward, dir, Vector3.up); // degrees, + = clockwise from above
Quaternion look = Quaternion.LookRotation(dir, Vector3.up);
float t = 1f - Mathf.Exp(-8f * Time.deltaTime); // frame-rate independent
transform.rotation = Quaternion.Slerp(transform.rotation, look, t);
// or at a constant speed: Quaternion.RotateTowards(transform.rotation, look, 180f * Time.deltaTime);Unreal (C++) is left-handed, Z-up, in centimeters, and an actor's forward is +X (GetActorForwardVector()). Since UE5, FVector holds doubles:
const FVector ToTarget = Target->GetActorLocation() - GetActorLocation();
const FVector Dir = ToTarget.GetSafeNormal();
const bool bInFront = FVector::DotProduct(GetActorForwardVector(), Dir) > FMath::Cos(FMath::DegreesToRadians(45.0));
const double Side = FVector::CrossProduct(GetActorForwardVector(), Dir).Z; // > 0: target is to the RIGHT
const FQuat Look = FRotationMatrix::MakeFromX(Dir).ToQuat(); // forward = +X
const double Alpha = 1.0 - FMath::Exp(-8.0 * DeltaTime);
SetActorRotation(FQuat::Slerp(GetActorQuat(), Look, Alpha));
// engine helpers: FMath::QInterpTo(Current, Target, DeltaTime, Speed),
// UKismetMathLibrary::FindLookAtRotation(Start, TargetLocation) returns an FRotatorGodot (GDScript) is right-handed, Y-up, and a node's forward is -Z (-global_transform.basis.z), the same as this course:
var to_target: Vector3 = target.global_position - global_position
var dir := to_target.normalized()
var forward := -global_transform.basis.z
var in_front := forward.dot(dir) > cos(deg_to_rad(45.0))
var side := forward.cross(dir).y # > 0: target is to the LEFT (right-handed)
var signed_yaw := forward.signed_angle_to(dir, Vector3.UP) # radians, + = counter-clockwise from above
var look := Basis.looking_at(dir, Vector3.UP).get_rotation_quaternion()
var t := 1.0 - exp(-8.0 * delta)
quaternion = quaternion.slerp(look, t) # Node3D.quaternion (local rotation)
# one-shot alternative: look_at(target.global_position, Vector3.UP)Three.js is right-handed, Y-up. Object3D.lookAt turns an object's +Z toward the point, but a camera's -Z; getWorldDirection follows the same rule:
import * as THREE from 'three';
const toTarget = new THREE.Vector3().subVectors(target.position, obj.position);
const dir = toTarget.clone().normalize();
const forward = obj.getWorldDirection(new THREE.Vector3()); // +Z for meshes, -Z for cameras
const inFront = forward.dot(dir) > Math.cos(THREE.MathUtils.degToRad(45));
// Matrix4.lookAt(eye, target, up) points -Z at the target (camera style); swapping eye and target
// points +Z at it, which is what Object3D.lookAt does for meshes.
const look = new THREE.Quaternion().setFromRotationMatrix(
new THREE.Matrix4().lookAt(target.position, obj.position, obj.up));
obj.quaternion.slerp(look, 1 - Math.exp(-8 * dt)); // or THREE.MathUtils.damp for numbers
// one-shot alternative: obj.lookAt(target.position)GLM (C++) is right-handed, Y-up and -Z forward by default (GLM_FORCE_LEFT_HANDED switches):
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
glm::vec3 dir = glm::normalize(target - position); // check the length first: NaN on zero
bool inFront = glm::dot(forward, dir) > std::cos(glm::radians(45.0f));
float side = glm::cross(forward, dir).y; // > 0: target is to the LEFT
glm::quat look = glm::quatLookAt(dir, glm::vec3(0, 1, 0)); // -Z forward
float t = 1.0f - std::exp(-8.0f * dt);
orientation = glm::slerp(orientation, look, t);Notice the sign of side: the same formula means "right" in the left-handed engines and "left" in the right-handed ones. The next lesson is about exactly this.
Transforms and spaces
| Task | Unity | Unreal | Godot | Three.js | GLM |
|---|---|---|---|---|---|
| local → world point | transform.TransformPoint(p) |
GetActorTransform().TransformPosition(P) |
to_global(p) or global_transform * p |
obj.localToWorld(p) |
glm::vec3(model * glm::vec4(p, 1)) |
| world → local point | transform.InverseTransformPoint(p) |
GetActorTransform().InverseTransformPosition(P) |
to_local(p) or global_transform.affine_inverse() * p |
obj.worldToLocal(p) |
glm::vec3(glm::inverse(model) * glm::vec4(p, 1)) |
| local → world direction | transform.TransformDirection(d) |
GetActorTransform().TransformVectorNoScale(D) |
global_transform.basis * d |
d.transformDirection(obj.matrixWorld) |
glm::mat3(model) * d |
| build TRS | Matrix4x4.TRS(p, q, s) |
FTransform(Q, P, S) |
Transform3D(Basis(q) * Basis.from_scale(s), p) |
new Matrix4().compose(p, q, s) |
translate * mat4_cast(q) * scale |
| view / projection | cam.worldToCameraMatrix, cam.projectionMatrix |
FViewMatrices (in render code) |
Projection / Camera3D.get_camera_projection() |
camera.matrixWorldInverse, camera.projectionMatrix |
glm::lookAt, glm::perspective |
| mouse ray | Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue()) |
PC->DeprojectMousePositionToWorld(Loc, Dir) |
cam.project_ray_origin(pos), cam.project_ray_normal(pos) |
raycaster.setFromCamera(ndc, camera) |
glm::unProject(win, view, proj, viewport) |
| world → screen | cam.WorldToScreenPoint(p) |
PC->ProjectWorldLocationToScreen(P, Screen) |
cam.unproject_position(p) |
p.clone().project(camera) (gives NDC) |
glm::project(p, view, proj, viewport) |
Scalar helpers
| Helper | Unity Mathf |
Unreal FMath |
Godot (global) | Three.js MathUtils |
GLM |
|---|---|---|---|---|---|
| inverse lerp | InverseLerp(a, b, v) |
GetRangePct(A, B, V) |
inverse_lerp(a, b, v) |
inverseLerp(a, b, v) |
(write it) |
| remap | (combine) | GetMappedRangeValueClamped(InRange, OutRange, V) |
remap(v, in_min, in_max, out_min, out_max) |
mapLinear(v, inMin, inMax, outMin, outMax) |
(write it) |
| smoothstep | SmoothStep(from, to, t) (an eased lerp!) |
SmoothStep(A, B, X) |
smoothstep(from, to, x) |
smoothstep(x, min, max) |
glm::smoothstep(e0, e1, x) |
| damping | SmoothDamp(cur, target, ref vel, time) |
FInterpTo(Cur, Target, Dt, Speed) |
(write 1 - exp(-k * delta)) |
damp(x, y, lambda, dt) |
(write it) |
| angles | DeltaAngle, MoveTowardsAngle (degrees) |
FindDeltaAngleDegrees, UnwindDegrees |
angle_difference, wrapf, lerp_angle |
euclideanModulo |
glm::atan(y, x) |
| nearly equal | Approximately(a, b) |
IsNearlyEqual(A, B, Tol) |
is_equal_approx(a, b) |
(write it) | glm::epsilonEqual (gtc/epsilon) |
| noise | PerlinNoise(x, y) (0..1) |
PerlinNoise2D(V) (-1..1) |
FastNoiseLite resource |
(none built in) | glm::perlin, glm::simplex (gtc/noise) |
Watch the argument orders: Three.js's smoothstep(x, min, max) puts x first, unlike GLSL and Godot. And Unity's Mathf.SmoothStep(from, to, t) is an eased lerp between from and to, not GLSL's edge function.
One gotcha you can run: Godot's reflect vs bounce
In Godot 4, Vector3.bounce(n) is the ball-off-a-wall reflection from the Projection lesson, and Vector3.reflect(n) mirrors the vector through the plane instead, which is the negation. Unity's Vector3.Reflect, Unreal's FMath::GetReflectionVector, Three.js's reflect and GLM's glm::reflect all match Godot's bounce. Here are both formulas side by side:
#include <iostream>
#include <iomanip>
#include <cmath>
struct Vec3 { double x, y, z; };
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }
// Unity Vector3.Reflect / Unreal GetReflectionVector / glm::reflect / Godot bounce:
Vec3 bounce(Vec3 v, Vec3 n) { return v - n * (2 * dot(v, n)); }
// Godot 4 Vector3.reflect: mirror through the plane (the opposite direction)
Vec3 godotReflect(Vec3 v, Vec3 n) { return n * (2 * dot(v, n)) - v; }
int main() {
std::cout << std::fixed << std::setprecision(1);
Vec3 ball{3, -4, 0}, floorN{0, 1, 0};
std::cout << "bounce (most engines): " << bounce(ball, floorN) << "\n";
std::cout << "Godot reflect: " << godotReflect(ball, floorN) << "\n";
}bounce (most engines): (3.0, 4.0, 0.0)
Godot reflect: (-3.0, -4.0, 0.0)
Test yourself
What is the forward axis of an actor in Unreal Engine?
- +Z
- -Z
- +X
- +Y
In Three.js, what does a.lerp(b, 0.5) do to a?
- Nothing; it returns a new vector
- It modifies a in place
- It modifies b
- It throws if a is const
Which Godot 4 method gives the same result as Unity's Vector3.Reflect(v, n) for a bouncing ball?
v.reflect(n)v.bounce(n)v.slide(n)v.project(n)