Home » Javascript » Js collision detector – hit the wall vs. hit the floor (difference)

Js collision detector – hit the wall vs. hit the floor (difference)

Posted by: admin September 23, 2018 Leave a comment

Questions:

Im making a small game with one player and blocks that builds up the envirement. The problem im having is knowing the difference between when the player hits the ground (the top of a block), and hitting a wall (the side of the block).

So far the player can walk on the ground just fine, but when he meets a wall, he immediately jumps to the top of that block.

This is my collision detector:

function collisionDetector(){
  if(myPlayer.y + myPlayer.h > c.height){	//Bottom of the canvas
    myPlayer.vy = 0;
    myPlayer.ay = 0;
    myPlayer.y = c.height - myPlayer.h;
    myPlayer.onGround = true;
    console.log(myPlayer.y + myPlayer.h, c.height);
  }
  if(myPlayer.x + myPlayer.w >= c.width){ //right side of canvas
    myPlayer.x = c.width - myPlayer.w;
    myPlayer.vx = 0;
  }
  if(myPlayer.x <= 0){ //Left side of canvas
    myPlayer.x = 0;
    myPlayer.vx = 0;
  }

  function hitTest(a,b){ //hitTest between two objects
    if(a.y + a.h > b.y && a.y < b.y + b.h && a.x + a.w > b.x && a.x < b.x + b.w){
      return true;
    }
  }

  for(var i = 0; i < blocks.length; i++){ //Loop through blocks
    if(hitTest(myPlayer, blocks[i])){ //If it touches a block
        myPlayer.y = blocks[i].y - myPlayer.h;
        myPlayer.onGround = true; //onGround = ready to jump
    }
  }
}
Answers: