title: Circle/rectangle collision response
body: <p>So I built some time ago a little <strong>Breakout clone</strong>, and I wanted to upgrade it a little bit, mostly for the collisions. When I first made it I had a basic "<em>collision</em>" detection between my ball and my brick, which in fact considered the ball as another rectangle. But this created an issue with the edge collisions, so I thought I would change it. The thing is, I found some answers to my problem:</p>
  
  <p>for example this image </p>
  
  <p><a href="https://i.stack.imgur.com/T5mxh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T5mxh.jpg" alt="enter image description here"></a></p>
  
  <p>and the last comment of this thread : <a href="https://www.allegro.cc/forums/thread/608207" rel="nofollow noreferrer">circle/rect collision reaction</a> but i could not find how to compute the final velocity vector.</p>
  
  <p>So far I have :</p>
  
  <p><strong>- Found the closest point on the rectangle</strong>,<br>
   <strong>- created the normal and tangent vectors</strong>,</p>
  
  <p>And now what I need is to somehow "divide the velocity vector into a normal component and a tangent component; negate the normal component and add the normal and tangent components to get the new Velocity vector" I'm sorry if this seems terribly easy but I could not get my mind around that ... 
  code :</p>
  
  <pre><code>function collision(rect, circle){
    var NearestX = Max(rect.x, Min(circle.pos.x, rect.x + rect.w));
    var NearestY = Max(rect.y, Min(circle.pos.y, rect.y + rect.w));
  
    var dist = createVector(circle.pos.x - NearestX, circle.pos.y - NearestY);
    var dnormal = createVector(- dist.y, dist.x);
  //change current circle vel according to the collision response
  }
  </code></pre>
  
  <p>Thanks !</p>
  
  <p>EDIT: Also found <a href="https://math.stackexchange.com/questions/428546/collision-between-a-circle-and-a-rectangle">this</a> but I didn't know if it is applicable at all points of the rectangle or only the corners.</p>