# Java2D Collision Detection

I've been wrapping my head around Java2D collision detection. I am working with Slick library and trying to figure a simple clean code to check if a collision has occurred.

The idea is fairly simple, I have an Entity class seen as a bound box (a rectangle in my case,but I am not using the intersects method), I am trying to run a check if current entity is colliding with any other entities passed in an arraylist:

    public boolean collides(Object o){
Entity e = (Entity) o;
return x + width > e.x && x < e.x + e.width && y + height > e.y && y < e.y + e.height;
}

public boolean collisidesAny(ArrayList al){
for(Object o: al){
return collides(o);
}
return false;
}


Now the thing with this code is that it gives me quite a bit of headache. The second method will return true the moment the objects do collide, and if I was to use it with a keyboard I wouldn't be able to move back since it won't allow any commands. Naturally I tried with sending the entity one step back when collision does occur, but the problem is I can't know where did it occur from, so I would have to do a step back both x and y wise. Other way I tried was a priori check, where I would check if a collision would occur if a step was made and if it wasn't I would allow the step, but this has gotten really complicated and buggy very quickly. Therefor I would like to know if there was a way to do collision this way?

Thanks for taking your time to read this, P.

• I suggest searching the site for collision detection. There are many dozens of questions about how to implement collision detection. – MichaelHouse Feb 19 '13 at 22:59
• I did do that, haven't found anything related to my case. – Mr.Potson Feb 19 '13 at 23:06
• There really are a flood of different discussions on collision-handling. It's one of the more popular topics around here. Incidentally, what you're describing is really collision-HANDLING, not collision detection, if that helps you find your solution. – Cameron Fredman Feb 19 '13 at 23:10
• I suppose I will look for that then, if I manage to find an answer I will gladly delete this post :) – Mr.Potson Feb 19 '13 at 23:12
• i have some code here that may be useful: gamedev.stackexchange.com/questions/25818/… – Ray Tayek Feb 20 '13 at 0:32