3 ms·
> Games calculate square roots and inverse square roots all the time to find the lengths of vectors A trick here is that one often doesn't have to do the squar
by matsemann 6y ago
> Games calculate square roots and inverse square roots all the time to find the lengths of vectors
A trick here is that one often doesn't have to do the square root. For instance, if you want something to happen when an object is 5 units away from another object, it's normal to do
if sqrt( (x2-x1)^2 - (y2-y1)^2 ) < 5 then ...
but instead you can do
if (x2-x1)^2 - (y2-y1)^2 < 5^2 then ...
trading a sqrt for a squaring. And often the square of the distance can be cached or even a constant. So a lot of libraries (for instance vector library from libgdx[0]) contain a dst function, but also a dst2 function that skips the squaring to save some cycles when not needed.
[0]: https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/badlogic/gdx/math/Vector2.html#dst2-com.badlogic.gdx.math.Vector2- https://libgdx.badlogicgames.com/ci/nightlies/docs/api/com/b...
- thdrdt 6y agoSometimes you can even get away by dropping the square completely: if (x2-x1) - (y2-y1) < (x4-x3) - (y4-y3) then ... I once used this in a path tracer to speed things up a little. The results where less accurate but sometimes this can be used as trade-off.
- TeMPOraL 6y agoI vaguely recall seeing in Graphics Gems an additional coefficient placed there that's been computed to minimize the error of this metric vs. Euclidean one.
- izackp 6y agohttps://gist.github.com/izackp/5ae96a740678946d8763c198b0e54d16 https://gist.github.com/izackp/5ae96a740678946d8763c198b0e54... I have a list of functions for distance calculation with metrics on speed and accuracy. If anyone would find it useful.