Lesson 3 of 7

3D math you actually need: vectors, distance, CFrame

The 3D math behind Roblox games, practised in runnable cells and through Beacon Yard's numbers: Vector3 offsets, distance with Magnitude, direction with Unit, dot products for facing checks, CFrame position and rotation, and lerp.

Concept lesson, about 70 minutes, 10 steps

By the end you can

  • Subtract positions to get an offset, and use Magnitude and Unit for distance and direction
  • Use a dot product to tell whether something is in front, beside or behind
  • Read and build a CFrame, apply it to an offset, and blend between points with lerp

Before this: Parts, models, materials and pivots

1Twelve studs

Later in Beacon Yard, one line inside CoinService decides whether you get paid. A touch event says your foot brushed the coin. The server does not trust that, so it measures:

		-- A touch is only a hint. Check the character's root is close
		-- enough to the coin before paying.
		local character = player.Character
		local rootPart = if character then character:FindFirstChild("HumanoidRootPart") else nil
		if rootPart == nil or not rootPart:IsA("BasePart") then
			return
		end
		if (rootPart.Position - coin.Position).Magnitude > 12 then
Figure 1.1

rootPart.Position - coin.Position is a vector: an arrow from the coin to your character. .Magnitude is that arrow's length in studs. More than 12, no coins. That one line uses most of the math in this lesson. You will practise every piece right here in runnable Vector3 and CFrame cells, without needing to know Studio scripting yet.

What does the number 12 in CoinService's check measure?

  1. The straight-line distance in studs between the character's root part and the coin
  2. How many times Touched fired
  3. The coin's value
  4. The X distance only
Answer

The straight-line distance in studs between the character's root part and the coin. Subtracting positions gives the offset between them; Magnitude is its length. A touch from more than 12 studs away is refused.

Open this step in lesson mode · Link to this step · This confused me

2A Vector3 is a walk

A Vector3Vector3Three numbers, X, Y and Z, used for positions, sizes and directions.Think of it as walking directions: so many studs along X, up and along Z. is three numbers: X, Y and Z. Y is up. In the yard, X runs east and west, Z runs north and south. Vector3.new(3, 0, 4) can mean "walk 3 studs along X and 4 along Z". It can also mean a place: "the point 3 along X and 4 along Z from the origin".

Both sidesVector3 is walk 3 east, 4 north.
In the pictureIn Roblox
A set of walking directionsA Vector3 offset
How far the walk isMagnitude
Which way to start walkingUnit

See the whole analogy cast

A Vector3 is a set of walking directions: so many studs along X, up and along Z. Add two and you follow one, then the other. Subtract a start from an end and you get the directions from the start to the end.

Think of it as Walk 3 east, 4 north

The rule you use most is subtraction. target - origin is the walk from origin to target. Order matters: origin - target is the same walk backwards.

Luau with roblox-lite (not Roblox)
local pad1 = Vector3.new(22, 0, 0)   -- the east coin pad
local spawn = Vector3.new(-30, 3, 0) -- the SpawnLocation from m01
 
local walk = pad1 - spawn
print("spawn to pad1:", walk)
print("pad1 to spawn:", spawn - pad1)
print("check:", spawn + walk)        -- start + walk = end
Figure 2.1. Expected output: spawn to pad1: 52, -3, 0 pad1 to spawn: -52, 3, 0 check: 22, 0, 0

Both sidesRemember: Vector3 is walk 3 east, 4 north.

The shop is at (28, 3, 28) and the beacon at (0, 1.5, 0). What does this print?

local shop = Vector3.new(28, 3, 28)
local beacon = Vector3.new(0, 1.5, 0)
print(beacon - shop)
  1. -28, -1.5, -28
  2. 28, 1.5, 28
  3. 28, 4.5, 28
  4. 0, 0, 0
Answer

-28, -1.5, -28. beacon - shop is the walk from the shop to the beacon: 28 studs back along X and Z and 1.5 down.

Open this step in lesson mode · Link to this step · This confused me

3Distance is Magnitude

The length of a walk is its MagnitudeMagnitudeThe length of a vector: the square root of X squared plus Y squared plus Z squared.Think of it as how long the walk is.: the square root of X² + Y² + Z², which is Pythagoras in three dimensions1. A walk of (3, 0, 4) is 5 studs long, not 7. That is why checking X and Z separately is a bug: a player 9 studs along X and 9 along Z passes both "under 12" checks, but is 12.7 studs away.

Luau with roblox-lite (not Roblox)
local coin = Vector3.new(22, 2.2, 0)   -- Pad1's coin, 2.2 above the pad
 
local function canCollect(root)
	return (root - coin).Magnitude <= 12
end
 
local near = Vector3.new(14, 3, 6)
local corner = Vector3.new(31, 3, 9)
print((near - coin).Magnitude, canCollect(near))
print((corner - coin).Magnitude, canCollect(corner))
Figure 3.1. Expected output: 10.031949043273926 true 12.75303840637207 false

Ways to ask "is it close enough?"

OptionWhat it isWhen pros pick itTrade-offs
Magnitude check(a - b).Magnitude <= range, one subtraction and a square root.A handful of checks: one coin, one drone, one prompt. What Beacon Yard does.Checking every player against every object each frame grows fast.
Squared distanceCompare the squared length with range * range and skip the square root.Tight loops over many objects, in code that runs every frame.A small speed-up that makes the code harder to read; measure before you bother.
Spatial queryworkspace:GetPartBoundsInRadius(point, radius, params) asks the engine for parts near a point.Many objects, or you do not know in advance which ones to test.Returns parts, not players; filter the results, and it costs more per call than one subtraction.
TouchedLet physics report contact.Cheap hints that something arrived, such as stepping on a pad.Fires many times, not from scripted movement, and a client can fake its own contacts; always confirm on the server.

A player stands 9 studs along X and 9 studs along Z from a coin, at the same height. How far away is the player, to one decimal place?

Answer

12.7 studs (within 0.05). √(81 + 81) = √162 ≈ 12.7 studs. Outside the coin's 12-stud range, even though each axis alone is under 12.

Open this step in lesson mode · Link to this step · This confused me

4Direction is Unit

Sometimes you want the way to go, not how far. .Unit keeps a vector's direction and makes its length exactly 1. Multiply a unit vector by a number and you get a walk of that many studs in that direction. When you build the wrench's raycast later in The wrench: tools, raycasts, tags, direction.Unit * 14 uses this exact trick to cap the reach at 14 studs.

The drone at m06-drone-wrench uses .Unit every frame too. It flattens the offset to the nearest player onto the ground (Y = 0, so it never dives), takes the unit direction, and moves DRONE_SPEED * dt studs along it, never closer than STOP_DISTANCE:

local function moveDrone(drone: Drone, dt: number)
	local root = drone.root
	local pos = Vector3.new(root.Position.X, HOVER_Y, root.Position.Z)
	local rotation = root.CFrame.Rotation
	local target = nearestLivingRoot(root.Position)
	if target then
		local flat = Vector3.new(target.Position.X - pos.X, 0, target.Position.Z - pos.Z)
		local distance = flat.Magnitude
		if distance > STOP_DISTANCE then
			local travel = math.min(Config.DRONE_SPEED * dt, distance - STOP_DISTANCE)
			local direction = flat.Unit
			pos += direction * travel
			rotation = CFrame.lookAt(Vector3.zero, direction).Rotation
		end
	end
	drone.model:PivotTo(CFrame.new(pos) * rotation)
Figure 4.1

One trap: a zero vector has no direction. .Unit of (0, 0, 0) divides by zero and gives NaN, "not a number", which then spreads into every position it touches. The drone avoids it because it only moves when the distance is greater than 3.

The vector playground

The vector playground: a still of the simulation
Figure 4.2.

Drag the player, the coin and the drone. The readout shows the offset, its Magnitude, its Unit vector and the dot product with the player's facing.

Open this step in lesson mode · Link to this step · This confused me

5In front or behind: the dot product

The dot productDot productOne number, from -1 to 1 for unit vectors, that says how much two directions agree.Think of it as a check on whether two arrows point the same way. of two unit vectors is one number between −1 and 1 that says how much they point the same way: 1 means the same direction, 0 means at right angles, −1 means opposite. It is the cosine of the angle between them.

That makes a cheap facing check. Take where a player is looking (LookVector, a unit vector), the unit direction to a target, and dot them. Above 0.5, the target is within 60° of straight ahead.

Luau with roblox-lite (not Roblox)
local look = Vector3.new(0, 0, -1)       -- facing -Z, like a fresh CFrame
local me = Vector3.new(0, 0, 0)
 
local function facing(target)
	return look:Dot((target - me).Unit)
end
 
print("ahead ", facing(Vector3.new(0, 0, -10)))
print("aside ", facing(Vector3.new(10, 0, 0)))
print("behind", facing(Vector3.new(0, 0, 10)))
print("ahead, far", facing(Vector3.new(0, 0, -200)))
Figure 5.1. Expected output: ahead 1 aside 0 behind -1 ahead, far 1

A facing check computes look:Dot((drone - player).Unit) and gets −0.9. What does that tell you?

  1. The drone is almost directly behind the player
  2. The drone is 0.9 studs away
  3. The drone is directly in front
  4. The player is standing still
Answer

The drone is almost directly behind the player. −0.9 is close to −1: the direction to the drone is nearly opposite to where the player is looking.

Open this step in lesson mode · Link to this step · This confused me

6CFrame: a position and a rotation

A part's position is a Vector3, but where it faces needs more. A CFrameCFrameA coordinate frame: a position and a rotation together.Think of it as a map pin with an arrow on it. ("coordinate frame") holds a position and a rotation together2:

  • CFrame.new(x, y, z) is a position with no rotation.
  • CFrame.Angles(rx, ry, rz) is a rotation, in radians. math.rad(90) turns degrees into radians.
  • CFrame.lookAt(from, to) sits at from and faces to.
  • cf.Position and cf.LookVector read it back. A CFrame with no rotation looks along −Z.
  • cf * offset turns an offset in the CFrame's own frame into a world position. "2 studs in front of the drone" is droneCFrame * Vector3.new(0, 0, -2).

The beacon's pedestal is a cylinder. Cylinders lie along X, so MapBuilder rolls it 90° on Z to stand it up: CFrame.new(0, 1.5, 0) * CFrame.Angles(0, 0, math.rad(90)). The drone turns to face where it is going with CFrame.lookAt(Vector3.zero, direction).

Both sidesCFrame is a map pin with an arrow.
In the pictureIn Roblox
The pinCFrame.Position
The arrow on the pinThe rotation, read as LookVector
Walk this far relative to the arrowcframe * offset

See the whole analogy cast

A CFrame is a map pin with an arrow on it: the pin says where, the arrow says which way. Multiplying by an offset means "from this pin, walk this far relative to the arrow".

Think of it as A map pin with an arrow

Luau with roblox-lite (not Roblox)
local drone = CFrame.lookAt(Vector3.new(0, 4, 18), Vector3.new(-30, 4, 0))
print("drone faces:", drone.LookVector)
 
local ahead = drone * Vector3.new(0, 0, -2)   -- 2 studs in front, in the drone's own frame
print("2 studs ahead:", ahead)
 
local spun = CFrame.new(0, 4, 18) * CFrame.Angles(0, math.rad(90), 0)
print("after a 90 degree turn it faces:", spun.LookVector)
Figure 6.1. Expected output: drone faces: -0.8574929, 0, -0.5144958 2 studs ahead: -1.7149858, 4, 16.971008 after a 90 degree turn it faces: -1, -0, -6.123234e-17

Both sidesRemember: CFrame is a map pin with an arrow.

Which direction does CFrame.new(0, 5, -45).LookVector point?

  1. Along −Z, because CFrame.new with only a position has no rotation
  2. Toward the origin (0, 0, 0)
  3. Straight up along +Y
  4. It is zero until you call CFrame.Angles
Answer

Along −Z, because CFrame.new with only a position has no rotation. An unrotated CFrame always has LookVector (0, 0, -1), pointing along −Z, regardless of its position.

Open this step in lesson mode · Link to this step · This confused me

7Where the pictures break

Both pictures in this lesson are useful and both have edges.

Where does it break?“Walk 3 east, 4 north” is a good picture of vector3. Where does it stop being true?

It breaks here. A Vector3 also stores a place: the same three numbers can be a walk from anywhere or a point measured from the origin, and only context says which.

The true model. A Vector3 is three numbers. As an offset it is a displacement; as a position it is the displacement from the origin. Subtracting positions gives the offset, and adding an offset to a position gives a new position.

Pad1 sits at Position Vector3.new(22, 0, 0). Is that a point or a move of 22 studs from wherever the pad was?

  1. A point 22 studs along world X from the origin
  2. A move of 22 studs from the pad's previous position
Answer

A point 22 studs along world X from the origin. Position is a point in the world. Adding the same Vector3 to the old position would use those three numbers as an offset instead.

Where does it break?“A map pin with an arrow” is a good picture of cframe. Where does it stop being true?

It breaks here. A pin's arrow points one way on a flat map, but a CFrame rotates in all three dimensions, and multiplying CFrames in a different order gives a different result.

The true model. A CFrame stores a position and a 3 by 3 rotation matrix. Multiplying composes them: a * b applies b in a's frame. The order matters because rotations do not commute.

Which line puts a part 5 studs in front of the drone, wherever the drone faces?

  1. drone * CFrame.new(0, 0, -5)
  2. CFrame.new(0, 0, -5) * drone
  3. drone + Vector3.new(0, 0, 5)
  4. drone.Position + Vector3.new(0, 0, -5)
Answer

drone * CFrame.new(0, 0, -5). cf * offset applies the offset in the drone's own frame. Putting the offset first, or adding a world Vector3, moves along the world's -Z regardless of where the drone faces.

Open this step in lesson mode · Link to this step · This confused me

8Lerp: part of the way there

LerpLerpLinear interpolation: the point a fraction t of the way from a to b.Think of it as part of the way there., short for linear interpolation, finds the point a fraction t of the way from a to b: a + (b - a) * t. At t = 0 you are at a, at 1 at b, at 0.5 exactly halfway. In Studio, a:Lerp(b, t) does it for Vector3 and cf:Lerp(other, t) for CFrames, which also blends the rotation.

Lerp and the drone's chase look similar but feel different. The drone moves a fixed 12 studs per second, so it arrives at a steady speed. Lerping a fixed fraction of the remaining distance every frame slows down as it gets close, which feels smooth for cameras and UI.

Luau with roblox-lite (not Roblox)
local function lerp(a, b, t)
	return a + (b - a) * t
end
 
local target = Vector3.new(10, 0, 0)
local smooth = Vector3.zero
local steady = Vector3.zero
for frame = 1, 5 do
	smooth = lerp(smooth, target, 0.5)            -- half the remaining way
	local gap = target - steady
	steady += gap.Unit * math.min(2, gap.Magnitude) -- 2 studs per frame
	print(frame, smooth.X, steady.X)
end
print("halfway:", lerp(Vector3.zero, target, 0.5))
Figure 8.1. Expected output: 1 5 2 2 7.5 4 3 8.75 6 4 9.375 8 5 9.6875 10 halfway: 5, 0, 0

What does this print?

local a = Vector3.new(0, 4, 18)
local b = Vector3.new(-30, 4, 0)
print(a + (b - a) * 0.5)
  1. -15, 4, 9
  2. -30, 4, 0
  3. -15, 8, 9
  4. 15, 4, 9
Answer

-15, 4, 9. Halfway from (0, 4, 18) to (−30, 4, 0) is (−15, 4, 9): the midpoint between the drone's spawn and the player spawn.

Open this step in lesson mode · Link to this step · This confused me

9Challenges

Level 1, Apprentice

Challenge

Without Studio, work out how far the spawn is from pad 1 and pad 4, and whether a player standing on the spawn could collect either coin.

Start from
Paper, or the Run cells above

Done means

  • You computed the distance from Spawn (−30, 3, 0) to each of Pad1 (22, 0, 0) and Pad4 (−22, 0, 0)
  • You said which pads are within 12 studs of the spawn

Hints

  1. Subtract, then take the length: √(X² + Y² + Z²).
  2. Pad4 is the pad on the spawn's side of the yard.

Level 2, Builder

Challenge

Practice Vector3 and CFrame directly in the browser runner below. When every assertion passes, the cell completes this challenge.

Start from
The Run cell below
Check it here
Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.

Done means

  • inRange returns true when a and b are at most range studs apart
  • pointAhead uses cf * Vector3.new(0, 0, -distance) to place a point in front of cf
  • midpoint returns the point halfway between a and b

Hints

  1. Subtract b - a and check .Magnitude <= range.
  2. A CFrame looks along -Z, so distance studs ahead is Vector3.new(0, 0, -distance).
Solution
luau
local function inRange(a, b, range)
	return (a - b).Magnitude <= range
end
 
local function pointAhead(cf, distance)
	return cf * Vector3.new(0, 0, -distance)
end
 
local function midpoint(a, b)
	return a + (b - a) * 0.5
end
Luau with roblox-lite (not Roblox)
-- Complete the three helpers using Vector3 and CFrame math.
local function inRange(a, b, range)
	return false
end
 
local function pointAhead(cf, distance)
	return cf.Position
end
 
local function midpoint(a, b)
	return a
end
Figure 9.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

Level 3, Professional

Challenge

Optional Studio stretch challenge: start from m14-ship and fill in the five functions in challenges/work/math_3d.luau. The : Vector3 and : number labels in that file are type annotations taught at the end of Module 2. The check is pure math. Press Play to start the Course Runner, then run this in the server command bar:

luau
game.ServerScriptService.RunGameTests:Invoke("math-3d")
Start from
The game at milestone m14 (download)
Grade it
In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("math-3d") in the server command bar. Copy the pass code from Output.

Done means

  • inRange, flatDirection, isFacing, chaseStep and lerp in challenges/work/math_3d.luau return the right values
  • flatDirection returns nil for points on top of each other instead of NaN
  • chaseStep stops 3 studs short and keeps the drone's own height

Hints

  1. inRange is CoinService's check with <= instead of >; chaseStep is moveDrone without the PivotTo.
  2. Guard before .Unit: if the flat offset's Magnitude is tiny, return nil (or stay put).
Solution
luau
function Math3D.chaseStep(pos: Vector3, target: Vector3, speed: number, dt: number, stopDistance: number): Vector3
	local flat = Vector3.new(target.X - pos.X, 0, target.Z - pos.Z)
	local distance = flat.Magnitude
	if distance <= stopDistance then
		return pos
	end
	return pos + flat.Unit * math.min(speed * dt, distance - stopDistance)
end

Open this step in lesson mode · Link to this step · This confused me

10Recap

Retiring the analogy

You no longer need “walk 3 east, 4 north”. A Vector3 is three numbers. As an offset it is a displacement; as a position it is the displacement from the origin. Subtracting positions gives the offset, and adding an offset to a position gives a new position.

Retiring the analogy

You no longer need “a map pin with an arrow”. A CFrame stores a position and a 3 by 3 rotation matrix. Multiplying composes them: a * b applies b in a's frame. The order matters because rotations do not commute.

Recap

  1. target - origin is the offset between two points; .Magnitude is its length in studs and .Unit its direction, never of a zero vector.
  2. The dot product of two unit vectors runs from 1 (same way) through 0 (sideways) to −1 (opposite): a cheap facing check.
  3. A CFrame is a position plus a rotation; cf * offset is relative to the CFrame and the order of multiplication matters. Lerp blends a + (b - a) * t.

Vector3 is walk 3 east, 4 north, until a Vector3 also stores a place: the same three numbers can be a walk from anywhere or a point measured from the origin, and only context says which.

CFrame is a map pin with an arrow, until a pin's arrow points one way on a flat map, but a CFrame rotates in all three dimensions, and multiplying CFrames in a different order gives a different result.

Next Building by hand: Terrain, solid modeling, Toolbox licensing, Packages

Open this step in lesson mode · Link to this step · This confused me