**Collision detection** also known as **hit testing** is simply determining when two objects come in **contact** with one another.

The collision of objects underlies most game experiences and user-interfaces.

Baseball bats collide with balls, zombies bump into walls, and Mario lands on platforms and stomps turtles.

#### A General Formula For Collision Detection

Detect the positions of each object, compare and calculate if they're overlapping.

#### Instances

Examples of collision between two objects:-

- POINT/POINT
- CIRCLE/CIRCLE
RECTANGLE/RECTANGLE

**Point/Point**

The easiest collision to test is between two points, to test if they're colliding, we simply check if their X and Y co-ordinates are the same! (i.e if their positions are same).

```
if (x1 == x2 && y1 == y2) {
// Points are in the same place: collision
}
else {
// Not colliding
}
```

**Circle ⭕ / Circle ⭕**

Imagine you have two circles, each with their own radius. They are placed with a distance between them. The circles would overlap if the **distance** is **smaller** than the **sum** of the **radius** of both circles.

Calculating the distance between the center of the two circles requires us to remember middle school math and the Pythagorean Theorem:

`Opp² + Adj² = Hyp²`

simply `∆x² + ∆y² = d²`

;

`d = √(∆x² + ∆y²)`

;

Translated to code, it looks like this:

```
d = Math.sqrt((∆x*∆x) + (∆y*∆y))
```

So, if this distance is smaller than or equal to the radius of circle-a plus radius of circle-b, the circles overlap or touch. This principle is used in the next function:

```
const circlesCollide = (x1, y1, r1, x2, y2, r2) => {
// Calculate the distance between the two circles
let squareDistance = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
// When the distance is smaller or equal to the sum
// of the two radius, the circles touch or overlap
return squareDistance <= ((r1 + r2) * (r1 + r2))
}
```

As you can see, the formula is tweaked a bit. Multiplication is much faster than getting the square root with

`Math.sqrt()`

so the distance is calculated without getting the root and the sum of the radii is multiplied by itself. The outcome stays the same, but the performance is better.

## Top comments (0)