0
votes

I basically made two walls in the canvas. One in the top and one at the bottom. My player is controlled by the MOUSE and I wanted to know how to make the player not go through the walls.

Here's the function for the general collision between two objects:

function collides(a, b) {
   var val = false;

   val = (a.x < b.x + b.width) &&
   (a.x + a.width > b.x) &&
   (a.y < b.y + b.height) &&
   (a.y + a.height > b.y);

   return val;        
}

Here's the code that detects collision detection:

if (collides(player, block)){
    //I don't know what goes here.
}

Any help would be appreciated.

1

1 Answers

0
votes

Reposition the player as you already do and also clamp the player's y position to always be between the top and bottom walls.

In your mousemove handler (or wherever the player is repositioned by the mouse):

// reposition the player as you already do
...

// and clamp the player to stay below the top wall
if( player.y < wall.y+wall.height ){ player.y = wall.y+wall.height);

// and clamp the player to stay above the bottom wall
if( player.y+player.height > wall.y ){ player.y = wall.y-player.height);