# Circle to Circle Collisions?

#### Amon

##### Member
How would I go about making Circle to Circle collisions in CX?

#### MikeHart

Look into fantomCX, there is a bunch of collision methods in one module. Sorry not at my comp. Let me know if you find it.

• Amon

#### Amon

##### Member
Thanks, Mike. I'll have a look now.

#### MikeHart

Did you found it? Here is one that just relies on the parameters:

Cerberus X:
``````'-----------------------------------------------------------------------------
Local xf:Float
Local yf:Float
Local rf:Float

xf = x1 - x2
xf *= xf
yf = y1 - y2
yf *= yf
rf *= rf
If (xf+yf) < rf Then Return True
Return False
End``````

• Amon

#### Amon

##### Member
You read my mind, Mike. I was just going to request this but you've don it already. lol

Thanks, Mike.

#### SLotman

##### Active Member
Circle-circle is easy: just get the distance between the center of both circles (using Pythagora's Theorem) and see if it's equal or smaller then the sum of the radius (radi?) of both spheres.

Once you know/understand that, you can write that function above with your eyes closed #### Gerry Quinn

##### Active Member
Circle-circle is easy: just get the distance between the center of both circles (using Pythagora's Theorem) and see if it's equal or smaller then the sum of the radius (radi?) of both spheres.

Once you know/understand that, you can write that function above with your eyes closed You don't need to take the square root, though, unless you want the actual distance. Comparing the squared distances is enough to test for a collision, and if your objects are mostly the same size or of a fixed size you can have the square of the sum of radii as a known value or a constant.

(Not so much a problem these days, but there was a time when sqrt() was expensive...)

• MikeHart

#### SLotman

##### Active Member
You don't need to take the square root
I know, it's a common optimization for that - the other one being xdiff = x2-x1; xdiff*=xdiff to avoid pow(2) If you want the ultimate speed, you can use the radii to build squares and do an AABB collision first, which doesn't involve any multiplication - and only test if the circles collide if the rects are colliding first Or you can even go crazy and do a quadtree on screen and test only the objects in the same quadrant as the player ^_^
(Those two of course are only necessary if you have tons of objects and collisions going on!)

#### Gerry Quinn

##### Active Member
Yeah, I always do the multiply, can't bring myself not to. I try to train myself not to care about speed when it doesn't matter, but sometimes leaving out the obvious optimisation seems unbearable. Even in the GUI...

• SLotman

#### SLotman

##### Active Member
I do it too! Sometimes I'm even worse, because my first computer, an MSX, had a Z80 as CPU, which doesn't have multiplication or division opcodes. So, whenever its possible you'll see me using bit shifting to multiply or divide BAD dinossaur, bad!! 