Using Vector3.Distance

Hi, I tried another approach and used Vector3.Distance to get the distance between enemy and player. Is there a downside by using this instead?

protected bool IsInChaseRange()
        float dist = Vector3.Distance(stateMachine.Player.transform.position, stateMachine.transform.position);
        return dist < stateMachine.PlayerChasingRange;

Nope. Perfectly fine. It’s (very) marginally more computationally heavy but you’re not going to notice it. The way Nathan did it removes the need to get the square root of the square magnitude, while Vector3.Distance(...) does get the square root. That’s all

1 Like

That’s basically the right of it. The way modern CPUs handle floating point processors, multiplication is always faster than division. This extends into Squares and Square Roots (owing that these are implemented using multiplication and division.

Vector3.Distance is calculated by taking the square root of the sums of (x1-x2)^2 + (y1-y2)^2 + (z1-z2)^2. So here we have three subtractions (average) three multiplications (fast!) two additions (fast) and one complex division (slow).
.magnitude is calculated by taking the square root of x^2 + y^2 + z^2. In the case of .magnitude, we’ve likely front loaded the Vector1 - Vector2 math (three subtractions), plus the aforementioned three multiplications, two additions and a complex division.
.sqrMagnitude is calculated by adding x^2 + y^2 + z^2. Once again, for our purposes, we’re still subtracting the vectors in advance, and now we have three multiplications and two additions. On the other end of the equation, we add one multiplication (PlayerChasingRange * PlayerChasingRange), but that replaces one of the CPU’s slowest math functions with one of the CPU’s fastest math function.

Ultimately, on a high end PC, you’re not likely to notice the difference, if 20 or 30 enemies make this square root transaction once a frame. On the average Android phone, however (most Android phones active in the world are older and slower and don’t do quite as well at math).

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms