Make an enemy follow the player in WoofJS

This tutorial explains how to make an enemy (or any object) follow the player (or another object) around in WoofJS, as shown in the example below.

image20

Create a project in WoofJS and add the following code. Make sure you pay attention to the comments in the code that explain how it works.

// Set the backdrop image
setBackdropURL("./docs/images/ocean.jpg")
// Make the backdrop fill the screen nicely
setBackdropStyle("cover")

// Create a player
var player = new Image({
  url: "./docs/images/sushi.png",
  width: 50, 
  height: 40,
  x: 200
})

// Create an enemy
var enemy = new Image({
  url: "./docs/images/crab.png",
  width: 50, 
  height: 40,
  x: -150
})

// Make speed variables for player and enemy
var playerSpeed = 8
var enemySpeed = 3

forever(() => {
  // Press arrow keys to move player
  
  // Make the player move up
  if (keysDown.includes('UP')) {
    player.y += playerSpeed
  }
  
  // Make the player move down
  if (keysDown.includes('DOWN')) {
    player.y -= playerSpeed
  }
  
  // Make the player move left
  if (keysDown.includes('LEFT')) {
    player.x -= playerSpeed
  }
  
  // Make the player move right
  if (keysDown.includes('RIGHT')) {
    player.x += playerSpeed
  }
  
  // Make the enemy point towards the player
  enemy.pointTowards(player)
  // Make the enemy move
  enemy.move(enemySpeed)
})