Let's say you have two points in the game, A and B. You frequently want to know the distance between the two items. For the sake of performance (since we will be calculating distances between objects several hundred times per frame), we leave the distance squared, and we just square any values we want to compare it to. Very simple.

Now, let's say that B is more than a point, and has a radius of R. Now we want to know the (squared) distance from A to the (nearest) outer surface of B, not just to the center of B. So we want the distance from A to (B - R).

I tried squaring R and subtracting that from the squared distance, but obviously the result was not correct.

Is there a way to calculate the reduced distance without using a sqrt to get the actual distance values? Can it be done with a reasonable level of calculation, or is sqrt the best option for this?

**1**

3 replies to this topic

Sponsor:

###
#2
Members - Reputation: **586**

Posted 09 May 2012 - 07:07 PM

I'm pretty rusty, but I don't think so because you can't just go around messing with the basic orders of operations in arithmetic. Did you try working it out on paper or a small program using 1D and some simple test data (ie. A = 0, B = 10, S = abs(B - radius)... for various radii such as 1,2,3,4,5)? Did you see a full-blown pattern in how the squared distances [ie. pow(S, 2.0) and pow(abs(A - S), 2.0)] change with respect to pow(abs(B - A), 2.0) = 100? If you did, please let me know.

**Edited by taby, 09 May 2012 - 07:11 PM.**

###
#3
Crossbones+ - Reputation: **17803**

Posted 09 May 2012 - 07:33 PM

If the distance between A and B is d and the radius is r, you are trying to compute n = (r-d)^2 = r^2+d^2-2*r*d. If it were possible to obtain this number without performing a square root, you could then compute

d = (r^2+d^2-n)/(2*r)

As you see, everything on the right-hand side can be computed without using square roots, so you would then be able to compute d without using a square root at all. This leads me to believe that what you are after is just not possible.

d = (r^2+d^2-n)/(2*r)

As you see, everything on the right-hand side can be computed without using square roots, so you would then be able to compute d without using a square root at all. This leads me to believe that what you are after is just not possible.