?The problem: measuring a distance
Constantly, a game asks itself “how far apart are these two points?”. Is the cannonball close to my tower? Which shell whistles the nearest?
The answer is the Pythagorean theorem. Between two points, we compute the horizontal gap dx and the vertical gap dy, and the distance is:
distance = Math.sqrt(dx*dx + dy*dy); // √(dx² + dy²)
It works perfectly… but that little Math.sqrt (the square root) is, historically, one of the most expensive operations a processor can do. Multiplying and adding is almost free; extracting a root, far less so. And in a game we ask for it thousands of times per second.
1The legend: 0x5f3759df
The anecdote you may remember is famous: the “fast inverse square root”, popularised by the source code of Quake III Arena (id Software, 1999 — the studio behind Doom, hence the frequent confusion!). To light a 3D scene, the engine had to normalise millions of vectors, which means computing a lot of 1 / √x.
Someone wrote this — a piece of code that became mythical for its colourful comment:
float Q_rsqrt(float number) { long i; float x2, y; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // read the float's bits as an integer i = 0x5f3759df - ( i >> 1 ); // what the f***? y = * ( float * ) &i; y = y * ( 1.5F - ( x2 * y * y ) ); // one Newton iteration to refine return y; }
The idea: a floating-point number is, in its bits, already a kind of logarithm. By shifting those bits (i >> 1) and subtracting a magic constant, you get an excellent first approximation of 1/√x — with no square root at all. A single pass of Newton's method refines the result. The whole thing is about 4× faster than the classic method of the time.
rsqrtss, vsqrt…) that's both faster and more accurate. In JavaScript, Math.sqrt calls that instruction directly: you won't beat it with bit tricks. The lesson isn't the recipe — it's the mindset: know the cost of what you compute.2The trick that still works: don't compute the root
The best optimisation is the operation you never do. And very often, we don't want the exact distance: we just want to compare it. “Is the ball less than 460 px away?” “Which of these shells is the closest?”
Key insight: the square root is a monotonically increasing function. If a² < b² (for positive distances), then a < b. So, to compare, we can compare the squares of the distances and skip the root entirely.
This is exactly what Tower Duel does for the proximity feedback on the phone. In turbo mode, several shells fly at once: we look for the one closest to your tower every frame. Instead of one root per shell, we compare the squares and extract only one root, right at the end, and only if a shell is within range:
let bestSq = Infinity; for (const p of s.projectiles) { const dx = p.x - ox, dy = p.y - oy; const d2 = dx*dx + dy*dy; // a square: just * and + if (d2 < bestSq) bestSq = d2; // we compare squares } // a single root, and only if something is in range const intensity = bestSq < threshold*threshold ? 1 - Math.sqrt(bestSq)/threshold : 0;
3Even better: skip Pythagoras too
To know whether a ball has hit a tower, we don't use distance at all. The tower is a rectangular box, so we just test whether the point is inside the box (AABB, axis-aligned bounding box): four comparisons, no multiplication, no root.
export function rectContains(rect, x, y) { return x >= rect.x && x <= rect.x + rect.w && y >= rect.y && y <= rect.y + rect.h; // 4 comparisons, done. }
And for the destructible terrain? A crater is a disc. “Is this point inside the crater of radius r?” amounts to “is its distance to the centre < r?”. We reuse the trick: we compare against the squared radius.
for (const c of craters) { const dx = x - c.x, dy = y - c.y; if (dx*dx + dy*dy <= c.r*c.r) return true; // no Math.sqrt }
Math.sqrt left serves the feel (the intensity of the buzz/whizz), not the game logic.4Your turn: square vs root
Distance to the centre
dx²+dy² ≤ r² — the same comparison as for a crater.5Bonus: the “smoothstep” easing
Same spirit on the turbo-mode wind: to glide smoothly from one value to another, we don't need expensive trigonometry. The smoothstep function gives a natural acceleration/deceleration with a simple polynomial:
const t = clock / WIND_KEY_SECONDS; // 0 → 1 between two keypoints const s = t * t * (3 - 2*t); // smoothstep: gentle at the start and the end const wind = from + (to - from) * s; // eased interpolation
Three multiplications and a subtraction, versus a sine, to get an S-curve. Cheap, readable, sufficient. That's the game's philosophy: each time, pick the simplest calculation that gives the desired effect.