Collision detection test fail, need help

So I been messing around doing random stuff with code and I just reached a point where I’m testing collision detection, one of the test I started with is the one on the pastebins I linked at the end of this post

What it’s supposed to do is to draw rectangles and they are supposed to bounce around the screen until it finds another rectangle or the border of the screen. It all works good until theres way too much rectangles and they start overlapping and it just is a mess, because they start changing direction like they should but its never supposed to overlap because they stay on the same position.

I hope someone understand what I’m trying to say, heres the links and thanks in advance for the help.

http://pastebin.java-gaming.org/930c87c26
http://pastebin.java-gaming.org/4872a892a
http://pastebin.java-gaming.org/025d09227

When your checking for collision, you set a new direction for travel, but you never check to see it this new direction (after one update) will cause overlap. So the code simply updates the positions, then come time for collision detection, lo-and-behold… you have two overlapping each other. Once they are overlapping they kinda stick because when they try to move away from each other their edges collide and your detection sends them the other way… does that make sense? I would be interested to see your solution, because checking for collisions a step ahead of your current state is not very easy to implement.

Haha yeah, I kind of though that was the problem, I’ll just have to dive in and make something since it looks like its alot of work

I’ll be thankful if anyone gives a hint tho

The problems with testing for ‘potential’ collisions is you have to check every single object that can collide against every other object that can collide TWICE! Once when you test for collisions the first time and second when choosing a new direction… perhaps create a system that only chooses a new direction for travel, but doesn’t actually move the objects. That way all the objects get new directions when they collide but still get a chance to test for collisions before moving in this new direction… just my thoughts, as I have never had a reason to do this, and am learning with you on this one! haha!

Try setting it to the old location when they intersect by creating an oldX and oldY variables in your loop. If they intersect, set the X and Y to the oldX and oldY.

Some thoughts about your code:
-Why call update twice with two different variables when you could update both at the same time with 1 call?
-This code:


public boolean intersectsWith(Figura intersector) {
      if (this.r.intersects(intersector.getR())) {
         return true;
      } else {
         return false;
      }
   }

Could be shrunk down to:


public boolean intersectsWith(Figura intersector) {
    return r.intersects(intersector.getR());
}

No idea xD