title: JS Arkanoid collision detection (sides vs bottom and top)
body: <p>I know there are many threads with similar questions, and I have read and tried many of them, but still i can't get the result I am looking for. Maybe someone can help me.</p>
  
  <p>I am writing a JS Arkanoid (Breakout) type game to improve my JS skills and I am having some trouble with the collision detection. Collision with the paddle or the walls is working, but not with the bricks.</p>
  
  <p>The ball and the bricks are instances of the classes Ball and Brick, each having it's own</p>
  
  <pre><code>pos: {
      x: ...
      y: ...
  }
  </code></pre>
  
  <p>The ball is draw from the center (<code>using ball.pos.x</code> and <code>ball.pos.y</code>) and it has a radius <code>ball.r</code>. The ball also has a x and y velocity (<code>ball.vel.x</code> and <code>ball.vel.y</code>).</p>
  
  <p>The bricks are drawn from the top left corner (<code>brick.pos.x</code> and <code>brick.pos.y</code>) and they have a height (<code>brick.h</code>) and width (<code>brick.w</code>). i also added a center point to the bricks (<code>brick.center.x</code> and <code>brick.center.y</code>).</p>
  
  <p>In the ball's update function I check for collisions with each brick like this:</p>
  
  <pre><code>for (let i = 0; i &lt; bricks.length; i++) {
      let collision = detectCollision(this, bricks[i]);
  }
  </code></pre>
  
  <p>and the detectCollisions is</p>
  
  <pre><code>function detectCollision(ball, brick) {
      let xDist = calculateDistance(ball.pos.x, brick.center.x);
      let yDist = calculateDistance(ball.pos.y, brick.center.y);
  
  if (xDist &lt; (ball.r + brick.w / 2) &amp;&amp; yDist &lt; (ball.r + brick.h / 2)) {
      return true;
  } else {
      return false;
  }
  
  function calculateDistance(pointA, pointB) {
      return Math.abs(pointA - pointB);
  }
  </code></pre>
  
  <p>I know now like this the code isn't really doing anything. i just store it in the <code>collision</code> variable. It is just to show you what my idea is. I can with this function detect if the ball and the brick collide, but can't detect with which side has the ball collided.</p>
  
  <p>What I now am missing and can't seem to understand is how to detect if the collision was with the top, the bottom, or one of the sides. If the collision was with the top or bottom i have to flip the <code>ball.vel.y</code> and if it was with one of the sides i have to flip the <code>ball.vel.x</code>.</p>