Every test in this chapter compares squared distances, with the squared distance function from the chapter on distance between two points:
type Point = { x: number; y: number };
function distanceSquared(a: Point, b: Point): number {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}function distanceSquared(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}import math
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
def distance_squared(a: Point, b: Point) -> float:
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2distanceSquared- time O(1) space O(1)
The equation of a circle
A circle is the set of all points at the same distance from its centre . Write that sentence with the distance formula, square both sides, and you have the equation of a circle:
Points inside the circle are closer to the centre than , so they satisfy the inequality
Point vs circle
That inequality already is a collision test. Is the cursor over a round button? Did a bullet hit a round enemy?
type Circle = { x: number; y: number; r: number };
function pointInCircle(p: Point, c: Circle): boolean {
return distanceSquared(p, c) <= c.r ** 2;
}// A circle is an object like { x: 200, y: 150, r: 40 }.
function pointInCircle(p, c) {
return distanceSquared(p, c) <= c.r ** 2;
}@dataclass
class Circle:
x: float
y: float
r: float
def point_in_circle(p: Point, c: Circle) -> bool:
return distance_squared(p, c) <= c.r ** 2pointInCircle- time O(1) space O(1)
A circle has an and a like a point, so the distance functions from the previous chapters take it as it is.
Circle vs circle
Two circles touch when the distance between their centres is at most the sum of their radii:
Another way to see it: grow one circle by the other’s radius, shrink the other one to a point, and you’re back to a point-in-circle test.
function circlesCollide(a: Circle, b: Circle): boolean {
return distanceSquared(a, b) <= (a.r + b.r) ** 2;
}function circlesCollide(a, b) {
return distanceSquared(a, b) <= (a.r + b.r) ** 2;
}def circles_collide(a: Circle, b: Circle) -> bool:
return distance_squared(a, b) <= (a.r + b.r) ** 2circlesCollide- time O(1) space O(1)
The circles on my home page run exactly this test.
Comments
No comments yet. Questions and corrections are welcome.