title: Detect which side of a rectangle is colliding with another rectangle
body: <p>i'm trying to develop a game using HTML5 canvas with javascript and I am having problems detecting collisions without hard coding it using the (x,y) coordinates of the two objects. In my code based from research, found out the common algorithm in checking if the two objects are colliding which is</p>
  
  <pre><code>Object1 = a moving player
  Object2 = fixed (x,y) points. Non movable object
  
  (object1.x &lt; object2.x + object2.width  &amp;&amp; object1.x + object1.width  &gt; object2.x &amp;&amp;
      object1.y &lt; object2.y + object2.height &amp;&amp; object1.y + object1.height &gt; object2.y)
  </code></pre>
  
  <p>I tried it and developed it with other codes and it works, it detects the collisions. But I have an issue with the collisions, it works with the condition in the <code>left side</code> but when the <code>object1</code> goes to the <code>top, bottom or right</code> of the object2 it goes back to the object2's <code>left side</code>. In other words, if the object1 goes to the top/bottom or right it goes back to the left side. Any kind of help would be much appreciated.</p>
  
  <pre><code>function collide(object1, object2){
  
      //object1 player
      this.x = object1.x;
      this.y = object1.y;
      this.w = object1.w;
      this.h = object1.h;
  
      //object2 any object 
      this.x2 = object2.x;
      this.y2 = object2.y;
      this.w2 = object2.w;
      this.h2 = object2.h;
  
      //collisions 
      var isCorrect = false;
      var side = 0;
  
      if ((this.x &lt; this.x2 + this.w2) &amp;&amp; (this.x + this.w &gt; this.x2) 
          &amp;&amp; (this.y &lt; this.y2 + this.h2) &amp;&amp; (this.h + this.y &gt; this.y2)){
          isCorrect = true;
      }
  
      if (this.x + this.w &gt; this.x2){
          //left check
          side = 1;
      }else if (this.x &lt; this.x2 + this.w2){
          //right check
          side = 2;
      }else if (this.y + this.h &gt; this.y2){
          //bottom check
          side = 3;
      }else if (this.y &lt; this.y2 + this.h2){
          //top check
          side = 4;
      }
  
      if (isCorrect){
          if ((this.x + this.w &gt; this.x2) &amp;&amp; side == 1){
              playerObj.x -= 5;
          }else if ((this.x &lt; this.x2 + this.w2) &amp;&amp; side == 2){
              playerObj.x += 5;
          }else if ((this.y + this.h &gt; this.y2) &amp;&amp; side == 3){
              playerObj.y += 5;
          }else if ((this.y &lt; this.y2 + this.h2) &amp;&amp; side == 4){
              playerObj.y -= 5;
          }
      }
  }
  </code></pre>