1
\$\begingroup\$

I'm currently coding a little circle to circle collision demo but I've got a little stuck. I think I currently have the code to detect collision but I'm not sure how to loop through my list of circles and check them off against one another.

Collision check code:

public static Vector2 GetIntersectionDepth(Circle a, Circle b) { float xValue = a.Center.X - b.Center.X; float yValue = a.Center.Y - b.Center.Y; Vector2 depth = Vector2.Zero; float distance = Vector2.Distance(a.Center, b.Center); if (a.Radius + b.Radius > distance) { float result = (a.Radius + b.Radius) - distance; depth.X = (float)Math.Cos(result); depth.Y = (float)Math.Sin(result); } return depth; } 

Loop through code:

 Vector2 depth = Vector2.Zero; for (int i = 0; i < bounds.Count; i++) for (int j = i+1; j < bounds.Count; j++) { depth = CircleToCircleIntersection.GetIntersectionDepth(bounds[i], bounds[j]); } 

Clearly I'm a complete newbie, wondering if anyone can give any suggestions or point out my errors, thanks in advance. :)

\$\endgroup\$
2
  • \$\begingroup\$ You have neglected to state what your actual problem is. Also, instead of comparing radii to distance, compare a.Radius*a.Radius + b.Radius*b.Radius > xValue*xValue + yValue*yValue. It is less work, both for you and the computer. \$\endgroup\$ Commented Mar 29, 2012 at 22:28
  • \$\begingroup\$ Superbeast is right. You could further optimize this by only using a sqrt operation when your circles actually overlap (to calculate the depth of intersection). Vector2.Distance uses sqrt which is computationally expensive. It would make a difference if you're checking a lot of circles for intersection. \$\endgroup\$ Commented Mar 30, 2012 at 6:48

1 Answer 1

2
\$\begingroup\$

The functions look correct assuming bounds is a Circle. The loop through code is also seems correct, as you are avoiding checking the same 2 circles again which is good.

For the collision detection bit, from the source your provided, the function GetIntersectionDepth(Circle a, Circle b) will return a zero vector IF the two circles are not colliding, so all you have to do is change your code to this:

Vector2 depth = Vector2.Zero; for (int i = 0; i < bounds.Count; i++) for (int j = i+1; j < bounds.Count; j++) { depth = CircleToCircleIntersection.GetIntersectionDepth(bounds[i], bounds[j]); if(depth == Vector2.Zero){ //this means that did not collide }else{ //this means they collided } } 
\$\endgroup\$
1
  • \$\begingroup\$ Nice work. Welcome to GameDev SE! \$\endgroup\$ Commented Mar 30, 2012 at 14:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.