How to keep the player within the screen in WoofJS

This tutorial explain how to make sure the player can’t disappear past any of the four edges of the screen in WoofJS, as show below.

image14

Go to WoofJS.com, create a new project and use the code below:

// Set the backdrop image
setBackdropURL("http://www.codemahal.com/sprites/grass_background.png")

// Create a speed variable for player movement
var speed = 5

// Create the player variable
var player = new Image({
  url: "https://www.codemahal.com/sprites/player.gif",
  width: 30, 
  height: 30,
  x: 0,
  y: 0
})

forever(() => {
  // Check if player has moved past right edge of screen
  if (player.x > maxX) {
    // Stop player moving right
    player.x = maxX
  }
  // Check if player has moved past left edge of screen
  if (player.x < minX) {
    // Stop player moving left
    player.x = minX
  }
  // Check if player has moved past top edge of screen
  if (player.y > maxY) {
    // Stop player moving up
    player.y = maxY
  }
  // Check if player has moved past bottom edge of screen
  if (player.y < minY) {
    // Stop player moving down
    player.y = minY
  }
  
  // Make player move up when pressing UP arrow key
  if (keysDown.includes('UP')) {
    player.y += speed
  }
  
  // Make player move down when pressing DOWN arrow key
  if (keysDown.includes('DOWN')) {
    player.y -= speed
  }
  
  // Make player move left when pressing LEFT arrow key
  if (keysDown.includes('LEFT')) {
    player.x -= speed
  }
  
  // Make player move right when pressing RIGHT arrow key
  if (keysDown.includes('RIGHT')) {
    player.x += speed
  }
})