javascript – Stopping the player when colliding with an object

Question:

I am designing a game. I found a way to detect the collisions:

var divPlayer = document.getElementById("div");
var div2 = document.getElementById("div2");
var pdiv1 = div1.getBoundingClientRect(),
  pdiv2 = div2.getBoundingClientRect();

if (
  pdiv1.right >= pdiv2.left &&
  pdiv1.left <= pdiv2.right &&
  pdiv1.bottom >= pdiv2.top &&
  pdiv1.top <= pdiv2.bottom
) {
  // Ejecutar codigo
}

But, I don't know how to prevent the player from going through the object when colliding with it.

Answer:

What you are doing there is detecting that the object is being touched (I understand that a wall is an object with the collision), what you would have to do is have another object that is not visible and that acts as a collision block (this is the one that will be in charge of verifying if it is going to crash or not). For that you have to move the collision object and if it collides with something. That it returns to the previous position and that the object or real player does not even move.

struct LastPositionCollision;
if (
  divPlayerCollision.right >= divPlayerCollision.left &&
  divPlayerCollision.left <= divPlayerCollision.right &&
  divPlayerCollision.bottom >= divPlayerCollision.top &&
  divPlayerCollision.top <= divPlayerCollision.bottom
   ){
    //Ha entrado en colisión con un objeto, no movemos al jugador y volvemos 
    //a resetear la posición del bloque de colisión

      Position = LastPositionCollision;
    }else{
    //No ha entrado en colisión con ningún objeto, movemos el jugador encima 
    //del bloque de colisión del jugador
    }
Scroll to Top