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.

A solution is to 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 requsted movement will take the player out of the canvas. If so, we don't update the player's coordintes.

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:

Go to Lesson 9 - Adding in bad guys