# Simple Bounding Sphere Calculations for 2d game

I'm writing a 2d game and have a question regarding the use of bounding spheres.

I'm kind of OK with the math, but I'm confused about one thing.

To work out the distance between the 2 centre points I've read that I need to do something like this:

XDistance = Sphere2_center - Sphere1_center.

And then some other calculations etc...

So if me Sphere1_center X is say, 100 pixels and my Sphere2_center is say 200, then the XDistance will equal to 100 which is fine, however, what confuses me is this. What happens if the positions of the spheres are reversed, then the 'code' would result in -100. This surely will affect the remainder of the calculations?

Not sure if I've got the whole thing wrong but I would be grateful if someone could advise. Many thanks

The distance between the center of the circles can be understood as the distance between two points.

You can calculate it as:

dx = p1.x - p2.x
dy = p1.y - p2.y
distance = sqrt(dx*dx + dy*dy)
// where p1 and p2 are two points (x,y) and sqrt is the square root


In your little example, using only the x coordinate:

distance_x = sqrt((p1.x-p2.x)*(p1.x-p2.x))

• Hi AranHase, thanks for the answer, so if in your example above, p1.x = 200 and p2.x = 100, then distance_x=sqrt(100)*(100) = 100. Am I getting this right? If the values of p1.x and p2.x are reversed, then it doesn't seem to work as p1.x-p2.x would give a negative answer - thanks for your continued help! – BungleBonce Dec 24 '12 at 18:47
• with p1.x = 100 and p2.x = 200 then dx = 100-200 = -100. Using the formula distance_x = sqrt(dx*dx) we have distance_x = sqrt(-100 * -100) = sqrt(+10000). So, distance_x = 100. You are multiplying two negative numbers, so the result is always positive. – Allan Hasegawa Dec 24 '12 at 18:53
• Brilliant - thanks so much for this, I was relying on my Widows calculator and not using my brain - the Windows calculator was telling me that -100 * -100 equals -200 lol of course this isn't so. Thanks so much for setting me right! :-) – BungleBonce Dec 24 '12 at 18:57
• Any idea how I check for collision? At the moment I'm comparing the distance (calculated as above) with the sum of the two bounding sphere's radii and when the former is less than the latter I carry out the collision routing. However, at the moment, it doesn't seem to work correctly - it carries out the collision routine but only as the sprite have passed each other and only on the Y plane. – BungleBonce Dec 24 '12 at 20:21
• Check this question: stackoverflow.com/questions/8367512/… If it did not solve your problem, open another question (i think). Also, I'm assuming you mean circle instead of sphere... – Allan Hasegawa Dec 24 '12 at 20:24

Aran's answer is exactly correct, but you could also do:

distance_x = Math.Abs(p1.x - p2.x);


So even if p1.x = 100 and p2.x = 200, 100-200 = -100, which the absolute value of is 100. I'm not sure if Abs is faster the sqrt, but it's less complicated.