Tutorial: How to make a top-down shooter in JavaScript

Lesson 8) Bounding the game area

It’s important to set boundaries

This lesson is just a little addendum to the previous one on collision detection. You may have noticed that it’s possible to take our player character right off the game area.

When the player’s x and y coordinates are outside the height or width of the canvas, he won’t be drawn, of course, but our keypress detectors and movement functions are still detecting input and updating his position.

We don’t want this. We want our player to stay inside the boundaries of the canvas, and asking nicely won’t be enough – we’ll have to use force.

One solution would be to create “walls” — rectangles at the edges of the screen, and use our collision function to see if the space the player is about to move into collides with any of these walls. If it does, we don’t allow the movement. This is what I would do to stop the player moving over objects in the middle of the game area, but for the edges, there’s another way.

We will make a little edit to our playerMove function. Instead of moving the player without question, we’ll add a little if statement into them, which checks if the requested movement will take the player out of the canvas. If so, we don’t update the player’s coordinates.

Without looking at my solution below, have a go at this yourself, and compare our results. Here’s what I came up with:

function playerMove(e){
  if (keys[87]) {
    if (Player1.y > 2) {
      Player1.y -= 2;
    }
  }
  if (keys[83] ) {
    if (Player1.y < HEIGHT - Player1.h - 2) { 
      Player1.y += 2; 
    } 
  } 
  if (keys[65] ) { 
    if (Player1.x > 2) {
      Player1.x -= 2;
    }
  }
  if (keys[68] ) {
    if (Player1.x < WIDTH - Player1.w - 2) {
      Player1.x += 2;
    }
  }
  return false;
}

Try it out below. You’ll find our rectangular buddy confined to the canvas:

Leave a Reply

Your email address will not be published. Required fields are marked *