2D Collision response disaster - what do?

So I’ve been coding off and on for about 2-3 years now. I’ve had this ongoing project that is a 2D game engine made with LWJGL. Its in a pretty finished state, but has a few quirks. One of those, happens to be collision response!

This is how I handle collisions between an entity and some other rectangle:

  1. Check if the two rectangles (java.awt.Rectangle rectangles that is) are intersecting
  2. Determine the position of the entity relative to the other rectangle (above, below, to the right, or to the left of it)
  3. Set the velocity of the entity to move in the opposite of the other rectangle, thus correcting the collision.

If I move the entity straight at a wall using the above technique to handle the collision, this can result in the entity moving back and forth rapidly, even at high framerates, instead of appearing still. Sometimes one of the rectangles can even clip into the other, and be stuck (this happens especially on corners).

Obviously this system isn’t sufficient, so what is a better way to do 2D collision response? Thank you!

If you want to move your entity back when collision happens it’s probably a good idea to post the piece of code where you handle the movement in case of collision. If instead you just want to avoid collision and don’t let entity end rectangle intersect you can easily use this approach:

  1. Update the entity position after have stored the precedent position
  2. Check if a collision happens, if so you just change the entity position to its precedent value
  3. If there are no collisions you just let the values as they are now and proceed to rendering

public void update(){
float oldX = entity.getX();
float oldY = entity.getY();

entity.setX(newPosition.x);
entity.setY(newPosition.y);

if(checkForCollision() == true){
entity.setX(oldX);
entity.setY(oldY);
}
}


if(checkForCollision()){
...
}

no need for the “== true”.

I perfectly know that ç_ç But this cose is without any sort of comment so I wanted to make sure that checkForCollision() returns a true value in case of collision…