Coordinate Geometry
Coordinate geometry puts shapes on the x-y grid, so that questions about lengths, angles and positions become arithmetic on numbers. A handful of formulas (distance, midpoint, slope, the distance from a point to a line) answer most of the geometry questions that come up in games, maps and drawing tools.
The core formulas
For points and :
| Quantity | Formula | Where it comes from |
|---|---|---|
| distance | Pythagorean theorem on the horizontal and vertical gaps | |
| midpoint | average of the coordinates | |
| point a fraction of the way from to | vectors (Vectors in Geometry) | |
| slope | rise over run | |
| parallel lines | same steepness | |
| perpendicular lines | one slope is the negative reciprocal of the other |
Line equations (slope-intercept , point-slope , and the general form ) are covered in Slope and Equations of Lines. A vertical line has no slope (the run is zero), which is one reason code often prefers direction vectors or the general form.
from fractions import Fraction
import math
A, B = (-2, 1), (4, 9)
M = (Fraction(A[0] + B[0], 2), Fraction(A[1] + B[1], 2))
m = Fraction(B[1] - A[1], B[0] - A[0])
perp = -1 / m
b = M[1] - perp * M[0] # perpendicular bisector y = perp·x + b passes through M
print("distance:", math.dist(A, B))
print(f"midpoint: ({M[0]}, {M[1]})")
print("slope:", m, " perpendicular slope:", perp)
print(f"perpendicular bisector: y = {perp}·x + {b}")
P = (5, 2) # a point on the bisector: −3/4·5 + 23/4 = 2
print("P on bisector?", P[1] == perp * P[0] + b, " dist to A, B:", math.dist(P, A), math.dist(P, B))distance: 10.0
midpoint: (1, 5)
slope: 4/3 perpendicular slope: -3/4
perpendicular bisector: y = -3/4·x + 23/4
P on bisector? True dist to A, B: 7.0710678118654755 7.0710678118654755
The perpendicular bisector of is the set of all points equally far from and , as the check on shows. Fraction keeps slopes exact instead of 1.3333…. Perpendicular bisectors of a triangle's sides meet at the circumcentre, the centre of the circle through all three corners (Circles).
Distance from a point to a line
The shortest distance from to the line is measured along the perpendicular:
Without the absolute value it is a signed distance whose sign says which side of the line is on. Three points are collinear (on one line) exactly when the triangle they form has zero area, which the 2D cross product tests with integers only:
import math
def point_line_distance(A, B, C, p):
return abs(A * p[0] + B * p[1] + C) / math.hypot(A, B)
def foot_of_perpendicular(A, B, C, p):
k = (A * p[0] + B * p[1] + C) / (A * A + B * B)
return (round(p[0] - A * k, 6), round(p[1] - B * k, 6))
print("distance from (5, 6) to 3x + 4y − 12 = 0:", point_line_distance(3, 4, -12, (5, 6)))
F = foot_of_perpendicular(3, 4, -12, (5, 6))
print("closest point on the line:", F, " check 3x + 4y =", round(3 * F[0] + 4 * F[1], 6))
def collinear(p, q, r):
return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) == 0
print("(1, 1), (3, 5), (6, 11) collinear?", collinear((1, 1), (3, 5), (6, 11)))
print("(1, 1), (3, 5), (6, 12) collinear?", collinear((1, 1), (3, 5), (6, 12)))distance from (5, 6) to 3x + 4y − 12 = 0: 5.4
closest point on the line: (1.76, 1.68) check 3x + 4y = 12.0
(1, 1), (3, 5), (6, 11) collinear? True
(1, 1), (3, 5), (6, 12) collinear? False
The distance agrees with . Snapping a dragged point onto a guide line in a drawing tool is exactly this foot-of-perpendicular calculation. See also Closest Point.
In software: distance and midpoint in games
Two of the most-run lines of game code are "who is closest?" and "where should the camera look?". Comparing squared distances skips the square root, since for non-negative numbers exactly when :
player = (0, 0)
enemies = {"slime": (3, 4), "bat": (-2, 6), "orc": (5, -1), "imp": (1, -5)}
def dist2(p, q):
return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
for name, pos in enemies.items():
print(f"{name:5} at {pos}: distance² = {dist2(player, pos)}")
nearest = min(enemies, key=lambda n: dist2(player, enemies[n]))
print("nearest:", nearest, " in attack range 5?", dist2(player, enemies[nearest]) <= 5 ** 2)
# a two-player camera: look at the midpoint, zoom out as the players separate
p1, p2 = (2, 3), (10, 9)
centre = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
separation = dist2(p1, p2) ** 0.5
print("camera centre:", centre, " view width:", max(8, separation + 4))slime at (3, 4): distance² = 25
bat at (-2, 6): distance² = 40
orc at (5, -1): distance² = 26
imp at (1, -5): distance² = 26
nearest: slime in attack range 5? True
camera centre: (6.0, 6.0) view width: 14.0
The midpoint is the case of linear interpolation; moving the camera a fraction of the way toward the target each frame gives a smooth follow (Lerp). More collision uses of these formulas are in Collision Geometry, and a review aimed at calculus is in Coordinate Geometry Review.
Exercises
Exercise 1: Distance and midpoint
Find the distance between and , and their midpoint.
Answer
Distance 10, midpoint .
Solution
Exercise 2: A perpendicular line
Find the equation of the line through perpendicular to .
Answer
Solution
Exercise 3: On one line?
Are , and collinear?
Answer
Yes.
Solution
Exercise 4: Point to line
How far is from the line ?
Answer
2
Solution
Exercise 5: A quarter of the way
A projectile flies in a straight line from to . Where is it after a quarter of the trip? Write a small function point_at(A, B, t) and check.
Answer
Solution
def point_at(A, B, t):
return (A[0] + t * (B[0] - A[0]), A[1] + t * (B[1] - A[1]))
print(point_at((2, 1), (10, 5), 0.25))(4.0, 2.0)
Test yourself
What is the midpoint of and ?
A line has slope 2/5. What is the slope of a line perpendicular to it?
- 2/5
- 5/2
- −5/2
- −2/5
Why do games compare squared distances to find the nearest enemy?
- Squared distances are more accurate
- The ordering is the same and it avoids computing square roots
- Square roots are not allowed in games
- Squared distances work only in 3D