Shiffman, Chapter 1

Vectors

The fundamental building block for programming motion — an entity with magnitude and direction.

Prerequisites: Basic algebra and coordinates. That's it.
10
Chapters
3
Simulations
10
Quizzes

Chapter 0: Why Vectors?

Imagine you're programming a bouncing ball. You need to track where it is and how fast it's moving. In the simplest approach, you'd write something like this:

pseudocode
x = 100
y = 100
xspeed = 1
yspeed = 3.3

each frame:
  x = x + xspeed
  y = y + yspeed

That works. But now imagine you want to add acceleration, wind, friction, a target location. Suddenly you need xacceleration, yacceleration, xwind, ywind, xfriction, yfriction… Two variables for every concept. In 3D, you'd need three.

The core idea: A vector bundles these paired values into a single object. Instead of x and y for location and xspeed and yspeed for velocity, you have location and velocity — each a vector. Cleaner code, and a rich set of mathematical operations comes for free.

This chapter introduces vectors from scratch. We'll learn what they are, how to add, subtract, multiply, and normalize them, and then use them to drive motion on screen. Every single example in the rest of this book depends on vectors.

Without vectorsWith vectors
x, y, xspeed, yspeed, xaccel, yaccellocation, velocity, acceleration
6 separate variables3 vector objects
Manual per-component mathBuilt-in operations (add, mult, mag, etc.)
Why do we use vectors instead of separate x,y variables?

Chapter 1: What Is a Vector?

A Euclidean vector is an entity with two properties: magnitude (how long it is) and direction (which way it points). We draw it as an arrow.

Think of it as an instruction: "Walk 3 steps east, then 4 steps north." That instruction has a direction (northeast-ish) and a magnitude (5 steps total, by the Pythagorean theorem). The instruction doesn't care where you start — it only describes a displacement.

Key distinction: A vector is not a position. It's a difference between two positions. But we can treat a position as the vector from the origin (0,0) to that point. This is why both location and velocity can be represented as vectors.

In code, a 2D vector is simply two numbers: an x component and a y component.

pseudocode
class Vector:
  x   # horizontal component
  y   # vertical component

Location? A vector: (x, y). Velocity? A vector: (xspeed, yspeed). Acceleration? A vector: (xaccel, yaccel). Same data structure, different meaning. The power comes from the operations we can perform on them.

ConceptAs a vectorMeaning
Location(200, 150)200px right, 150px down from origin
Velocity(3, -1)Moving 3px right and 1px up per frame
Acceleration(0, 0.1)Speeding up by 0.1px/frame downward
What two properties define a Euclidean vector?

Chapter 2: Vector Addition

The most fundamental vector operation is addition. If velocity tells you "how much to move per frame," then updating your location is just adding the velocity vector to the location vector:

location = location + velocity

Mechanically, we add component-by-component:

(x1, y1) + (x2, y2) = (x1 + x2, y1 + y2)

For example: location (5, 3) + velocity (2, -1) = new location (7, 2). The object moved 2 pixels right and 1 pixel up.

Tip-to-tail: Geometrically, adding two vectors means placing the tail of the second at the tip of the first. The result is the arrow from the first vector's tail to the second vector's tip. This is exactly what happens when velocity "pushes" the location forward each frame.
pseudocode
function add(v):
  x = x + v.x
  y = y + v.y

This single operation — adding velocity to location — is the engine behind every moving object in this entire book. Forces will change velocity (Chapter 2), and velocity will change location. It's vectors all the way down.

(3, 5) + (-1, 2) = ?

Chapter 3: Vector Subtraction

If addition answers "where will I end up?", subtraction answers "how do I get from here to there?" Subtracting one vector from another gives us the vector between them:

(x1, y1) − (x2, y2) = (x1 − x2, y1 − y2)

Example: target is at (300, 200), I'm at (100, 150). The vector from me to the target is (300 − 100, 200 − 150) = (200, 50). That tells me: go 200 pixels right and 50 pixels down.

This is huge: Vector subtraction gives us direction to a target. This concept reappears everywhere: gravitational attraction, steering behaviors, mouse following, collision avoidance. If you want an object to move toward something, you start by subtracting locations.

Geometrically, A − B is the vector from B's tip to A's tip (when both are drawn from the origin). Or equivalently, A + (−B): flip B around and add it tip-to-tail.

Target is at (400, 300), object is at (100, 100). What vector points from object to target?

Chapter 4: Vector Playground

Time to see vectors in action. Below you can drag two vector endpoints and watch addition and subtraction in real time. The orange arrow is vector A, the teal arrow is vector B, and the purple arrow shows their sum (A + B) using the tip-to-tail method.

Vector Addition & Subtraction

Drag the orange and teal arrowheads. The purple arrow shows A + B. The dotted arrow shows A − B. Components shown numerically below.

A = (0, 0) B = (0, 0) A+B = (0, 0)
What to notice: As you drag A or B, the sum (purple) always completes the parallelogram. The tip-to-tail rule means the sum arrow starts at the origin and ends where B's tip would be if B started at A's tip. This is the geometric meaning of vector addition.
In the tip-to-tail method of vector addition, where does the resulting vector point?

Chapter 5: Multiply & Divide

We can scale a vector by multiplying it by a scalar (a single number). This changes the magnitude without changing the direction:

n × (x, y) = (n × x, n × y)

Multiply by 2: the vector is twice as long, same direction. Multiply by 0.5: half as long. Multiply by −1: same length, opposite direction.

Division is just multiplication by the reciprocal: dividing by 3 is the same as multiplying by 1/3. We'll use this when normalizing vectors and when dividing force by mass (Newton's second law, Chapter 2).
OperationExample: v = (3, 4)Result
v × 2(3×2, 4×2)(6, 8)
v × 0.5(3×0.5, 4×0.5)(1.5, 2)
v × −1(3×−1, 4×−1)(−3, −4)
v / 5(3/5, 4/5)(0.6, 0.8)

Scalar multiplication is essential for controlling speed. Want your object to move twice as fast? Multiply its velocity by 2. Want to slow it down by half? Multiply by 0.5. Want to reverse direction? Multiply by −1.

What does multiplying a vector by -1 do?

Chapter 6: Magnitude

How long is a vector? Its magnitude (or length) is computed using the Pythagorean theorem. For a vector (x, y):

|v| = √(x2 + y2)

Example: the vector (3, 4) has magnitude √(9 + 16) = √25 = 5. If this were a velocity, the object moves 5 pixels per frame. The direction is "3 right, 4 down" but the speed is 5.

Speed vs velocity: Velocity is a vector (direction + magnitude). Speed is just the magnitude of velocity — a scalar. An object moving at velocity (3, −4) has a speed of 5.

In code, we compute magnitude and sometimes use magnitude squared (magSq = x*x + y*y) to avoid the expensive square root when we only need to compare magnitudes (e.g., "is this object within 100 pixels?" becomes "is magSq < 10000?").

pseudocode
function magnitude():
  return sqrt(x * x + y * y)

function magnitudeSquared():
  return x * x + y * y
What is the magnitude of vector (5, 12)?

Chapter 7: Normalization

To normalize a vector means to make its magnitude equal to 1, while keeping the same direction. The result is called a unit vector.

v̂ = v / |v|

Take vector (3, 4) with magnitude 5. Divide each component by 5: (3/5, 4/5) = (0.6, 0.8). Check: √(0.36 + 0.64) = √1 = 1. The direction is preserved but the length is now exactly 1.

Why normalize? A unit vector gives you pure direction. You can then scale it to any desired magnitude. Want a velocity pointing northeast at speed 7? Normalize the direction vector and multiply by 7. This pattern appears constantly: direction = target - location; direction.normalize(); direction.mult(maxSpeed);

This is exactly how Shiffman implements the "mouse follower" example. The object computes a vector pointing from itself to the mouse, normalizes it (to get the direction), and then multiplies by a desired speed. Without normalization, the object would teleport to the mouse instead of gliding toward it.

pseudocode
function normalize():
  m = magnitude()
  if m > 0:
    x = x / m
    y = y / m
Edge case: Never divide by zero. If the vector is (0, 0), its magnitude is 0 and normalization is undefined. Always check that magnitude > 0 first.
What is the magnitude of a normalized vector?

Chapter 8: Motion

Everything we've learned comes together here. Motion in this book follows a simple chain:

Acceleration
Changes velocity each frame
Velocity
Changes location each frame
Location
Where the object appears on screen
velocity = velocity + acceleration
location = location + velocity

This two-line update is the heartbeat of every simulation in the book. In the demo below, the ball accelerates toward your mouse (or toward a draggable target on touch devices). The acceleration vector is computed using subtraction and normalization:

pseudocode
dir = target - location     # vector pointing to target
dir.normalize()              # make it unit length
dir.mult(0.5)                # scale to desired accel
acceleration = dir
Motion: Acceleration Toward Target

Move your mouse (or drag on touch) to set the target. The ball accelerates toward it. Watch velocity accumulate — the ball overshoots and orbits because there's no friction.

vel = (0, 0)
Why does it orbit? There's no friction or damping. The ball accelerates toward the target, overshoots (because velocity doesn't go to zero when it arrives), and swings around. This is exactly how gravitational orbits work. Add damping (multiply velocity by 0.99 each frame) and the ball would spiral inward instead.
In the motion algorithm, what two lines are applied every frame?

Chapter 9: Summary

Vectors are the foundation for everything that follows. Here's what we've built:

OperationWhat it doesUsed for
add(v)Component-wise additionApplying velocity to location
sub(v)Component-wise subtractionFinding direction to target
mult(n)Scale by a numberControlling speed
div(n)Scale by 1/nDividing force by mass (F = ma)
mag()Pythagorean lengthMeasuring speed, distance
normalize()Make unit lengthGetting pure direction
The motion algorithm: velocity += acceleration; location += velocity; — two lines that power every bouncing ball, every particle, every autonomous agent in this book. Acceleration is where the "nature" enters. Gravity, wind, steering — they all produce an acceleration vector.

What we covered:

• Vectors as (x, y) pairs
• Addition (tip-to-tail)
• Subtraction (direction between points)
• Scalar multiplication/division
• Magnitude (Pythagorean)
• Normalization (unit vectors)
• Location/velocity/acceleration

What comes next:

Chapter 2: Forces. We learn that acceleration doesn't just appear — it comes from forces. Newton's second law (F = ma) tells us force = mass × acceleration. We'll apply gravity, wind, friction, and drag to our vector-based movers.

To make an object move toward a target at a fixed speed, what three vector operations do you apply (in order)?