It is safe to say that CPUs are relatively good at multiplying floating-point numbers together, but relatively dreadful at calculating square roots from them. Every time we ask a Vector3
to calculate a distance with the magnitude
property or with the Distance()
method, we're asking it to perform a square root calculation (as per the Pythagorean theorem), which can cost a lot of CPU overhead compared to many other types of vector math calculations.
However, the Vector3
class also offers a sqrMagnitude
property, which is the same as distance, only squared. This lets us perform essentially the same comparison check without the expensive square root included, so long as we also square the value we're trying to compare it against; or, to describe this mathematically, if the magnitude of A is less than the magnitude of B, then A2 will be less than B2.
For example, consider code like the following:
float distance = (transform.position – other.transform...