← Collision detection for beginners

[Chapter 3 · Part I · 2D]

Midpoint of a line segment

The point exactly halfway between two others, which is just the average of their coordinates.

The midpoint

Point SS is the midpoint of the line segment ABAB when it lies on the segment and AS=BS|AS| = |BS|. Its coordinates are the averages of the endpoints’ coordinates:

xS=xA+xB2,yS=yA+yB2x_{S} = \frac{x_{A} + x_{B}}{2}, \quad y_{S} = \frac{y_{A} + y_{B}}{2}
SAB
Drag A or B. S = ((120 + 500) / 2, (190 + 70) / 2) = (310, 130) · |AS| = |BS| = 199
TypeScript
function midpoint(a: Point, b: Point): Point {
	return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
}
JavaScript
function midpoint(a, b) {
	return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
}
Python
def midpoint(a: Point, b: Point) -> Point:
    return Point((a.x + b.x) / 2, (a.y + b.y) / 2)
midpoint
time O(1) space O(1)

Where it’s useful

The midpoint is handy whenever you need the point halfway between two things, like aiming a camera between two players, or putting a hit effect between two objects that bumped into each other. It’s also the centre of a segment, which the chapter on line segments comes back to.

Comments

No comments yet. Questions and corrections are welcome.

Plain text, line breaks kept. Your IP address is stored only as a one-way hash, to limit spam.