title: Find which side of square circle is on
body: <p>I'm building some collision detection into my 2D game, and I've got a method to test the collision and find the depth and normal of the collision, but I'm stuck on trying to figure out on which side the collision occured.</p>
  <p>The CirclePosition and the RectPosition here are the center of the shapes. I am using OpenGL so positive Y = down and negative Y = up.</p>
  <p>The objects I'm testing with are a circle and a square. These shapes are axis aligned.</p>
  <p>So my question is:</p>
  <p><strong>How can I detect which side of the square is the circle has hit?</strong></p>
  <p>This is the code I have so far:</p>
  <pre><code>enum side {
      SideLeft,
      SideRight,
      SideAbove,
      SideBelow,
  };
  
  typedef struct {
      int Collided;
      float Depth;
      float2 Normal;
      side Side;
  } collision;
  
  collision CircleRectIntersection(float2 CirclePosition, float Radius, float2 RectPosition, float2 Size) {
      float Top = RectPosition.Y - (Size.Y / 2);
      float Left = RectPosition.X - (Size.X / 2);
      float Bottom = RectPosition.Y + (Size.Y / 2);
      float Right = RectPosition.X + (Size.X / 2);
      
      float ExtentX = Size.X / 2;
      float ExtentY = Size.Y / 2;
      
      float2 N = RectPosition - CirclePosition;
      float2 Closest = N;
      Closest.X = Clamp(-ExtentX, ExtentX, Closest.X);
      Closest.Y = Clamp(-ExtentY, ExtentY, Closest.Y);
      
      bool Inside = false;
      if(N == Closest) {
          Inside = true;
          if(fabs(N.X) &gt; fabs(N.Y)) {
              if(Closest.X &gt; 0) Closest.X = ExtentX;
              else Closest.X = -ExtentX;
          }
          else {
              if(Closest.Y &gt; 0) Closest.Y = ExtentY;
              else Closest.Y = -ExtentY;
          }
      }
      
      float2 Normal = N - Closest;
      float D = LengthSquare(Normal);
      float R = Radius;
      
      D = sqrt(D);
      
      collision C;
      if(D &gt; R &amp;&amp; !Inside) {
          C.Collided = 0;
          return C;
      }
      
      if(Inside) C.Normal = -N;
      else C.Normal = N;
      
      C.Depth = R - D;
      
      return C;
  }
  </code></pre>
  <p>And here is some example code of how I would expect this to work:</p>
  <pre><code>int main(int argc, char **argv) {
     float2 RectPosition = float2(100, 100);
     float2 RectSize = float2(100, 100);
  
     float2 CirclePosition = float2(150, 100);
     float2 Radius = 20.0f;
  
     collision C = CircleRectIntersection(CirclePosition, Radius, RectPosition, RectSize);
    
     // here I would expect C.Side to be side.Right, as the circle is to the right of the rect
  }
  </code></pre>