# Subtraction between squared distances

This topic is 2080 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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?

##### Share on other sites
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

##### Share on other sites
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.