View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# Subtraction between squared distances

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

3 replies to this topic

### #1Nairou  Members

Posted 09 May 2012 - 06:04 PM

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?

### #2sjhalayka  Members

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Álvaro  Members

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.

### #4Nairou  Members

Posted 10 May 2012 - 12:43 PM

Thank you for the replies, looks like modifying the squared distance is a no-go. On the other hand, I have since found that I can add the radius into the other side of my distance comparison and get the same result, so all is well.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.