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.