When comparing distances, whether it be for collision detection in games or drawing circles or discs (like in this recent Geeks3D post) I often see people using sqrt when they are comparing distances. This sqrt is not needed and only wastes CPU or GPU time.

The distance between two points is calculated by taking the length of the vector between the two points, in other words by taking the square root of the dot product of the difference between the two points.

If we do circle or sphere collision detection, we need to compare the sum of the radii with the distance between the centers:

If this equation evaluates to true, the circles or spheres collide. Though as you can see, we can get rid of the sqrt by squaring both sides:

In case of the circle drawing in the GLSL shader we only have to calculate this squared radius once and pass it as a uniform. But even if we would have to do it each frame like in the case of collision detection, a multiplication is a lot faster than a square root.

Don’t use pow to square btw, use a simple multiplication. The pow method should only be used when the power to be used is unknown at compile time.

### Like this:

Like Loading...

*Related*

Tags: optimization

## Leave a Reply