How to flip the player to look in each direction (and change costumes) in WoofJS

This tutorial explains how to flip a player sprite to look in each direction when walking left or right (in WoofJS), as shown below. To achieve this, we just change the player costume by specifying a different URL (link) for the image.

image23

Create a project at woofjs.com and add the following code. Pay attention to the comments in the code that explain how it works.

// Set the backdrop image
setBackdropURL('https://www.codemahal.com/sprites/blue_background.png')

// Make a variable for player movement speed
var speed = 3


// Add the left-facing player image
var player = new Image({
  url: 'https://codemahal.com/sprites/player_left.gif',
  height: 50,
  width: 40,
  x: 0,
  y: 0,
})

forever(() => {
  // If left arrow key is pressed...
  if(keysDown.includes('LEFT')){
    // Set player image to left-facing
    player.setImageURL('https://codemahal.com/sprites/player_left.gif')
    // Move the player
    player.x -= speed
  }
  if(keysDown.includes('RIGHT')){
    // Set player image to right-facing
    player.setImageURL('https://codemahal.com/sprites/player_right.gif')
    // Move the player
    player.x += speed
  }
})