title: Physics Simulation Ensuring Circles Do Not Overlap - C# XNA 4.0
body: <p>Okay, so I am trying to simulate the collision of balls on a 2-Dimensional plane. I can detect the collisions pretty easily using a simple comparison of positions and the sum of radii, however, sometimes the simulation gets ahead of itself and the circles overlap, which plays havoc with the rest of the simulation.</p>
  
  <p>So I have figured that finding the normal vector between the two circles at the point of contact and adding onto the position vectors in that direction is what I need to do basically, and luckily I had a similar algorithm handling the velocity changes due to collisions so I adapted it thusly:</p>
  
  <pre><code>Vector2 normal = orgA.getCenterPosition() - orgB.getCenterPosition();
  Vector2 tangent = new Vector2((normal.Y * -1), normal.X);
  
  float diff = (orgA.getRadius() + orgB.getRadius()) - normal.Length();
  
  normal.Normalize();
  
  float PAn = Vector2.Dot(normal, orgA.position);
  float PAt = Vector2.Dot(tangent, orgA.position);
  
  PAn += diff;
  
  float PBn = Vector2.Dot(normal, orgB.position);
  float PBt = Vector2.Dot(tangent, orgB.position);
  
  PBn -= diff;
  
  Vector2 PA = (PAn * normal) + (PAt * tangent);
  Vector2 PB = (PBn * normal) + (PBt * tangent);
  
  orgA.position = PA;
  orgB.position = PB;
  </code></pre>
  
  <p>The trouble is that when I run the simulation, and two balls meet, the whole thing goes crazy and they're suddenly going all over the shop.</p>
  
  <p>Can anyone see the flaw in my algorithm? I've looked at it loads and I still can't find what's causing this.</p>