title: Collision in 2D game
body: <p>I'm trying to make a little game, where you have a little cube you can control with the arrows. When the cube intersects with another block object, I want it to go back and stop by the edge of the block object. So basically I want my block to stop when it intersects the block object, instead, it moves a bit in to it, and then when I move it again it jumps back. How can I make it so first checks if it will intersect, and if it will not move into it? </p>
  
  <p>My drawing class extends <code>JPanel</code> and I'm painting with <code>paintComponent</code>.</p>
  
  <pre><code> if(keyCode == e.VK_RIGHT) {
          if(xRightCollision()){
              hero.x -= xVel;
          }
          else {
              hero.x += xVel;
          }
      }
  </code></pre>
  
  <p>So let's say the cube is at the edge of the block object, but it's not intersecting it yet, so I press right and it moves into it, I press right again and it jumps back 5 pixels(xVel = 5). </p>
  
  <pre><code>public boolean xRightCollision(){
      for(int i = 0; i &lt; obstacles.size(); i++) {
          if (hero.intersects(obstacles.get(i))) {
              return true;
          }
      }
      return false;
  }
  </code></pre>
  
  <p>I've actually tried a similar thing with paint() on the <code>JFrame</code>, and since you have to call <code>repaint()</code> there, I could check first and then repaint. I don't really understand how <code>paintComponent</code> works since you can't control when it should be repainted.</p>