The best way to make a rectangular collision is to use the Rectangle class to detect a collision using the .intersects(Rectangle) method, and then compute a new variable called displacementX and displacementY .
displacementX = Math.abs(entitiy1.getX() - entity2.getX());
displacementY = Math.abs(entitiy1.getY() - entity2.getY());
So, currently the number of pixels of entity1 superimposed on entity2 (or vice versa due to the absolute value). Then do some comparisons and move entity1 (or entity2 ) to a value of less displacement , which should provide a perfect collision.
This is at least how I do it. The correct method for a rectangular collision:
1) Determine if they encountered
2) fix it
3) Render
Simply preventing movement after collision detection will look awful (especially at low frame rates).
I hope I helped!
~ Izman
Izman source share