Tag Archives: javascript

Creating an emoji chase game with WoofJS

In this tutorial, you will learn how to create a game where the player is being chased and has to keep running for as long a possible without getting caught by the flying emoji. The smiley emoji has to avoid being caught by the ghost emoji. You can customise this game as much as you like with your own characters.

emojirun

Step 1

Go to woofjs.com, login and create a new project. The first thing we will do is change the backdrop colour. You can either provide the name of the desired colour eg. setBackdropColor(“green”) or if you want to use a specific colour you can use a colour code (colour codes begin with a # and contain a combination of 6 numbers and letters from a to f). You can find colour codes at www.codemahal.com/colourpicker. You can also use an image for your backdrop if you like (refer to the previous two tutorials).

Add the following line of code for a light green backdrop:

setBackdropColor("#8CFFC2")

emoji1

Step 2

Now we will create the player sprite. For the player sprite will use an emoji image, set its width and height to 40 and position it in the middle of the screen (0 on the x and y axis). Add the following code:

var player = new Image({
   url: “http://www.codemahal.com/sprites/smiley.png”,
   height: 40,
   width: 40,
   x:0,
   y:0
})

Tip: All of this code can be squashed into one line but to make it easier to read here, each property for the player variable has been added on a new line.

emoji2

Step 3

Next, we can add the “Game over” message text and “Press P to play again” text which will display on screen at the end of the game. Once you have added the two text objects, set them to be hidden using the gameOverText.hide() and playAgainText.hide() lines.

Add the following code:

var gameOverText = new Text({
  x: 0,
  y: 80,
  fontFamily: "Lato",
  size: 30,
  color: "#0B9957",
  text: "Game over!"
});
var playAgainText = new Text({
  x: 0,
  y: 40,
  fontFamily: "Lato",
  size: 20,
  color: "#0B9957",
  text: "Press P to play again"
});

gameOverText.hide()
playAgainText.hide()

Step 4

Now we can add movement for the player object. To do this, create a forever loop and add if statements checking if the arrow keys have been pressed on the keyboard. Add the relevant movement on the x or y axis for the player object in each if statement. Here is the code:

forever(() => {
  if (keysDown.includes('UP')) {
    player.y += 7;
  }
  if (keysDown.includes('DOWN')) {
    player.y -= 7;
  }
  if (keysDown.includes('RIGHT')) {
    player.x += 7;
  }
  if (keysDown.includes('LEFT')) {
    player.x -= 7;
  }
});

Now you should be able to move the player object (smiley emoji) around the screen using the arrow keys on the keyboard.

emoji3

Step 5

Now that we are able to move the player around, we can add enemies (in the form of ghost emojis) that will spawn in random locations at each edge of the screen pointing towards the player. Firstly, we create an empty array (an array is like a list) called enemies which will be used to store all of the enemy clones that will spawn during the game.

We will use the same enemy sprite (a ghost emoji) for each individual enemy but every half a second, clone the enemy sprite and then use random number variable to determine which position the enemy clone should start from at different edges of the screen. Once the enemy clone spawns at a random location at the edge of the screen it will be pointed towards the player and added to the enemies array.

var enemies = [];
every(0.5, "seconds", () => {
  var enemy = new Image({
    url: "http://www.codemahal.com/sprites/ghost.png",
    height: 30,
    width: 30,
    x: 0,
    y: 0
  })
  var randomNumber = random(1, 4);
  if (randomNumber == 1) {
    enemy.x = randomX();
    enemy.y = maxY;
  }
  if (randomNumber == 2) {
    enemy.x = randomX();
    enemy.y = minY;
  }
  if (randomNumber == 3) {
    enemy.x = maxX;
    enemy.y = randomY();
  }
  if (randomNumber == 4) {
    enemy.x = minX;
    enemy.y = randomY();
  }
  enemy.pointTowards(player.x, player.y);
  enemies.push(enemy);
});

emoji4

Step 6

Now that we can clone enemy sprites at different edges of the screen and point them towards the player, we will need to actually make them move towards the player. We can add a forever loop which will constantly get each individual enemy clone in the enemies array and move them (remember, each enemy clone is pointing towards the position of where the player was when that enemy clone spawned, so the enemy clones will move towards the player). We also make sure that each cloned enemy sprite is showing. Add the following code:

forever(() => {
  enemies.forEach(enemy => {
    enemy.move(6);
    enemy.show()
  })
});

emoji5

Step 7

Now we can setup the timer which records how long the player has been running around for without being caught by an enemy. First, we create a timer variable set to 0. Then we create the text which will display the timer on screen. Then, every second we increase the timer by 1 and display the updated time on screen. Add the following code:

var timer = 0
var timerText = new Text({
  x: 0,
  y: maxY - 60,
  fontFamily: "Lato",
  size: 30,
  color: "red",
  text: () => 'Timer: ' + timer
});

every(1, "second", () => {
  timer++;
  timerText.text = 'Timer: ' + timer
});

At this point this is what the game should look like:

emoji6

Step 8

Now we can add a forever loop which will go through each enemy that exists in the enemies array and check if they are touching the player. If an enemy touches the player, then the “Game over” and “Press P to play again” text will be displayed on screen. The player object will also be hidden and the freeze() function will be called which will freeze the screen.

forever(() => {
  enemies.forEach(enemy => {
    if (enemy.touching(player)) {
      gameOverText.show()
      playAgainText.show()
      player.hide()
      freeze();
    }
  })
});

emoji7

Step 9

Next, we add another forever loop. In this forever loop we check if the P key is pressed on the keyboard and if so, then show the player object on screen, hide the “Game over” and “Press P to play again” messages, and go through all the enemy clones which exist in the enemies array and delete each one. The enemies array is set to be an empty array again, the timer is set to 0, the player object is moved back to the centre of the screen, and the defrost() function is called which un-freezes the game. Add the following code:

forever(() => {
  if(keysDown.includes("P")){
    player.show()
    gameOverText.hide()
    playAgainText.hide()
    enemies.forEach(enemy => enemy.delete())
    enemies = []
    timer = 0
    player.x = 0
    player.y = 0
    defrost();
  }
})

emoji8

Step 10

The final step is to add some code which will ensure the player cannot leave the screen. By adding the following code in a forever loop, we can constantly check if the player is going beyond any edges of the screen, and if so, stop them going any further. Add the following code to your game:

forever(() => {
  if (player.x > maxX) {
    player.x = maxX;
  }
  if (player.x < minX) {
    player.x = minX;
  }
  if (player.y > maxY) {
    player.y = maxY;
  }
  if (player.y < minY) {
    player.y = minY;
  }
});

This is what the game and code will look like once you’re done!

emoji9

Now play your game and see how long you can last without getting caught by a ghost emoji! You can try adding a high score feature to the game and also adjust some of the variables to increase or decrease the speed of the enemy movements depending on how challenging you want the game to be. You could have the enemies start off moving slowly and gradually build up speed over time too. Make sure you save your work!

Complete code

// Based on the game at woofjs.com/create.html#poop-emoji

setBackdropColor("#8CFFC2")
var player = new Image({
  url: "http://www.codemahal.com/sprites/smiley.png",
  height: 40,
  width: 40,
  x: 0,
  y: 0
}) 

var gameOverText = new Text({
  x: 0,
  y: 80,
  fontFamily: "Lato",
  size: 30,
  color: "#0B9957",
  text: "Game over!"
});
var playAgainText = new Text({
  x: 0,
  y: 40,
  fontFamily: "Lato",
  size: 20,
  color: "#0B9957",
  text: "Press P to play again"
});

gameOverText.hide()
playAgainText.hide()

forever(() => {
  if (keysDown.includes('UP')) {
    player.y += 7;
  }
  if (keysDown.includes('DOWN')) {
    player.y -= 7;
  }
  if (keysDown.includes('RIGHT')) {
    player.x += 7;
  }
  if (keysDown.includes('LEFT')) {
    player.x -= 7;
  }
});

var enemies = [];
every(0.5, "seconds", () => {
  var enemy = new Image({
    url: "http://www.codemahal.com/sprites/ghost.png",
    height: 30,
    width: 30,
    x: 0,
    y: 0
  })
  var randomNumber = random(1, 4);
  if (randomNumber == 1) {
    enemy.x = randomX();
    enemy.y = maxY;
  }
  if (randomNumber == 2) {
    enemy.x = randomX();
    enemy.y = minY;
  }
  if (randomNumber == 3) {
    enemy.x = maxX;
    enemy.y = randomY();
  }
  if (randomNumber == 4) {
    enemy.x = minX;
    enemy.y = randomY();
  }
  enemy.pointTowards(player.x, player.y);
  enemies.push(enemy);
});

forever(() => {
  enemies.forEach(enemy => {
    enemy.move(6);
    enemy.show()
  })
});

var timer = 0
var timerText = new Text({
  x: 0,
  y: maxY - 60,
  fontFamily: "Lato",
  size: 30,
  color: "red",
  text: () => 'Timer: ' + timer
});

every(1, "second", () => {
  timer++;
  timerText.text = 'Timer: ' + timer
});

forever(() => {
  enemies.forEach(enemy => {
    if (enemy.touching(player)) {
      gameOverText.show()
      playAgainText.show()
      player.hide()
      freeze();
    }
  })
});

forever(() => {
  if (keysDown.includes("P")) {
    player.show()
    gameOverText.hide()
    playAgainText.hide()
    enemies.forEach(enemy => enemy.delete())
    enemies = []
    timer = 0
    player.x = 0
    player.y = 0
    defrost();
  }
})

forever(() => {
  if (player.x > maxX) {
    player.x = maxX;
  }
  if (player.x < minX) {
    player.x = minX;
  }
  if (player.y > maxY) {
    player.y = maxY;
  }
  if (player.y < minY) {
    player.y = minY;
  }
});

Coding an apple catcher game with WoofJS

In this tutorial, you will learn how to create an apple catcher game using JavaScript code in WoofJS. The aim of the game is to catch as many falling apples as you can and beat the high score.

applegame

Step 1

Add a background (backdrop) for the game. You can make your own backdrop or use one provided at codemahal.com/sprites such as the sky background used below.

To add a backdrop, use the following line of code with the link (URL) to your backdrop image:

setBackdropURL('http://www.codemahal.com/sprites/sky_background.png')

apple1

Step 2

The next step involves creating a variable that will store the user’s high score and display the high score text on screen. Firstly, we will create a highScore variable. In order to save the high score we will need to access to the user’s local storage using the code localStorage.getItem. We will store the high score in the user’s storage using the name “userhighscore”. However, if this is the user’s first time playing the game and they have no high score, then the high score will be set to 0. Add the following line of code:

var highScore = localStorage.getItem("userhighscore") || 0;

The line of code above basically can be interpreted as: When the game begins create a variable in the game called highScore, and set it to store the high score value that was saved last time this game was played by the user (using the name “userhighscore”), or if no high score exists then set the high score to 0.

Next, display the high score on screen using the following code:

var highScoreText = new Text({
  text: () => "High score: " + highScore,
  x: minX + 20,
  y: maxY - 20,
  size: 24,
  fontFamily: 'Arial',
  color: "yellow",
  textAlign: "left"
})

Your game should now look like this:

apple2

Step 3

Now that we have the high score displayed on screen we can go ahead and add the text heading for the current score on screen using the following code:

var scoreHeadingText = new Text({
  text: "Score:",
  x: 0,
  y: 100,
  size: 30,
  color: "blue",
  fontFamily: "Arial",
  textAlign: "center"
})

Your game should now look like this:

apple3

Step 4

When the game ends we will want to display a “Game over” message to the user and ask the user if they wish to play again. We can create this text to display on screen stored in two variables (gameOverText and playAgainText) and hide the text immediately so it doesn’t display until the game is over. Add the following lines of code:

var gameOverText = new Text({
  text: "GAME OVER",
  x: 0,
  y: 0,
  size: 50,
  color: "red",
  fontFamily: "Arial",
  textAlign: "center"
})

var playAgainText = new Text({
  text: "Press P to play again",
  x: 0,
  y: -50,
  size: 20,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

gameOverText.hide()
playAgainText.hide()

apple4

Step 5

Next, we create a variable to store the score for the current game which will be set to 0 at the beginning of the game, and we create the text to display the current score on screen (under the score heading text).

var score = 0;
var scoreText = new Text({
  text: score,
  x: 0,
  y: 60,
  size: 32,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

apple5

Step 6

Now we can create the apple and player object. The apple will be represented by a circle and the player will be represented by a rectangle/bar which can move left and right. To add the apple and player object, add the following code:

var apple = new Circle({
  radius: 10,
  color: "red",
  x: random(-160, 160),
  y: maxY-50
})

var player = new Rectangle({
  width: 40,
  x: 0,
  y: minY+20,
  height: 20,
  color: "green"
})

The game should now look like this:

apple6

Step 7

Now that we have created the apple and player objects, we can set the speed at which the apple will fall to the ground (eg. 8) and the player movement which will be controlled by the mouse (when the mouse moves left the rectangle moves left, when the mouse moves right the rectangle moves right). In a forever loop, we will make the rectangle (player) follow the position of the mouse movement on the x axis and make the apple fall at the set speed in a negative direction (down) on the y axis). Add the following code:

var appleSpeed = 8
forever(() => {
  player.x = mouseX
  apple.y -= appleSpeed
})

You’ll notice once the apple falls past the bottom of the screen it will keep falling! We will add some code shortly which will make the apple respawn at the top of the screen again.

apple7

Step 8

Inside the forever loop we just added, we can add code which will check if the apple is touching the player (rectangle) and if so, we will move the apple back to the top of the screen (on y axis) and in a random position across the screen (on x axis) so it can fall again. We will also increase the current score by 1, update the score text on screen to reflect the current score, check if the current score is higher than the high score and if so, update the high score. Make sure you close all brackets for the forever loop and if statements.

Add the following code inside the forever loop we added in the previous step:

if (apple.touching(player)) {
    apple.x = random(-160, 160)
    apple.y = maxY-50
    score = score + 1;
    scoreText.text = score;
    if (score > highScore) {
      highScore = score
      localStorage.setItem("userhighscore", highScore)
    }
}

apple8

Step 9

Now we need to add code which will end the game if the apple falls and the player doesn’t catch it (in other words, if the apple falls below the bottom edge of the screen). This will display the “Game over” message on screen and ask the player to press P to play again. We created this text earlier but it is hidden while the game is running. By adding the code below, the “Game over” and “Press P to play again” text will show at the end of the game.

Add the following code inside the forever loop we used in the previous steps. This code will check if the apple has fallen below the bottom edge of the screen, and if it has then the “Game over” and “Press P to play again” text will be displayed on screen.

if (apple.y < minY) {
    gameOverText.show()
    playAgainText.show()
}

When the game ends the screen should look like this:

apple9

Step 10

When the game ends, the player should be given an opportunity to play again. We can use an if statement to check if the P key on the keyboard is pressed by the user. If the P key is pressed we can set the score back to 0, reset the score text on screen to reflect a score of 0, hide the gameOverText and playAgainText text objects, and move the apple back up to the top of the screen so it can start falling again and so the player can start catching apples again. The apple speed will also be reset to 8 (in the next step we will make the apple speed increase over time). Add the following code inside the forever loop:

if (keysDown.includes('P')) {
    score = 0
    scoreText.text = score;
    gameOverText.hide()
    playAgainText.hide()
    apple.x = random(-160, 160)
    apple.y = maxY – 50
    appleSpeed = 8
}

This is what the game should now look like:

apple10

The last step is to add extra challenge to the game which involves making the apple’s speed increase over time. We can add some code so that every 10 seconds the apple’s falling speed variable will increase by 1. Outside the forever loop and at the very end of the code, add the following lines of code:

every(10, "seconds", () => {
  appleSpeed = appleSpeed + 1
})

And that’s it! This is what the completed game should look like:

apple11

Make sure you save your code! If you click on the  icon at the top right corner of the screen then the game will open in full screen in a new tab. You can also share the link in that tab with your friends so they can play your game.

What next?

  • Try changing the code so the game makes more use of the space available when playing in full screen
  • Try using keyboard controls to move the player object rather than the mouse
  • You could use an apple image instead of a circle for the apple object
  • You could also add sound effects or background music

The complete code

setBackdropURL('http://www.codemahal.com/sprites/sky_background.png')
var highScore = localStorage.getItem("userhighscore") || 0;
var highScoreText = new Text({
  text: () => "High score: " + highScore,
  x: minX + 20,
  y: maxY - 20,
  size: 24,
  fontFamily: 'Arial',
  color: "yellow",
  textAlign: "left"
})

var scoreHeadingText = new Text({
  text: "Score:",
  x: 0,
  y: 100,
  size: 30,
  color: "blue",
  fontFamily: "Arial",
  textAlign: "center"
})

var gameOverText = new Text({
  text: "GAME OVER",
  x: 0,
  y: 0,
  size: 50,
  color: "red",
  fontFamily: "Arial",
  textAlign: "center"
})

var playAgainText = new Text({
  text: "Press P to play again",
  x: 0,
  y: -50,
  size: 20,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

gameOverText.hide()
playAgainText.hide()

var score = 0;
var scoreText = new Text({
  text: score,
  x: 0,
  y: 60,
  size: 32,
  color: "orange",
  fontFamily: "Arial",
  textAlign: "center"
})

var apple = new Circle({
  radius: 10,
  color: "red",
  x: random(-160, 160),
  y: maxY - 50
})

var player = new Rectangle({
  width: 40,
  x: 0,
  y: minY + 20,
  height: 20,
  color: "green"
})

var appleSpeed = 7
forever(() => {
  player.x = mouseX
  apple.y -= appleSpeed

  if (apple.touching(player)) {
    apple.x = random(-160, 160)
    apple.y = maxY - 50
    score = score + 1;
    scoreText.text = score;
    if (score > highScore) {
      highScore = score
      localStorage.setItem("userhighscore", highScore)
    }
  }

  if (apple.y < minY) {
    gameOverText.show()
    playAgainText.show()
  }

  if (keysDown.includes('P')) {
    score = 0
    scoreText.text = score;
    gameOverText.hide()
    playAgainText.hide()
    apple.x = random(-160, 160)
    apple.y = maxY - 50
    appleSpeed = 8
  }

})

every(10, "seconds", () => {
  appleSpeed = appleSpeed + 1
})

Creating your first 2D game in WoofJS

In this tutorial, you will learn how to code your first 2D game in the JavaScript programming language using WoofJS – a free website for coding games! To get started making your own games in JavaScript, go to www.woofjs.com and click Start Coding.

The first game we will make is a 2D game where you have to move around and using the keyboard to catch as many monsters as you can in 20 seconds.

catchmonster

Step 1

Make sure you create your free account so you can save your games to your profile. Click on Login / Sign up and then provide your email address. On the next screen.

woof_step1

Step 2

Once you have created your account and logged in, click on your account name in the top left corner and then click New Project.

woof_step2

Step 3

A new empty project will open. Click on Save in the top right corner. Make sure you save your work regularly while you are coding.

woof_step3_a

Then give your project a name and click OK.

woof_step3_b

This is what the WoofJS window looks like…

woof_step3_c

Step 4

As you can see in the image above, there is already one line of code there. This line of code is used to specify the background for the game (or at least this part of the game – you might have many different levels and menus in your game, but let’s just start with one level). setBackdropURL is a function which takes a link (also known as URL, or Uniform Resource Locator) to an image (such as a GIF, PNG or JPG) and uses that image for the background or backdrop.

The link goes inside brackets and single quotes (you can use single or double quotes but they must be matching). For example, for a grass background add this code using the free image on CodeMahal.com:

setBackdropURL("http://www.codemahal.com/sprites/grass_background.png")

Tip: You can create your own game sprites (backgrounds, characters and other objects) at piskellapp.com and use those sprites in your WoofJS game. You can also download free sprites to use in your project from codemahal.com/sprites.

So now we have a nice grass backdrop for the game. The game can be played in full screen but at the moment we can just see a preview of it on the left side of the screen.

woof_step4

Step 5

Now that we have a backdrop, we can add our first character to the game which will be the player. We can use an image sprite for the player too so we will need to specify the image to use for the player before we can specify its width, height, position, etc.

Add the following line of code to specify the image sprite to use for the player:

var playerImage = 'http://www.codemahal.com/sprites/player.gif';

You have just used the var keyword to create a variable. A variable is like a container that is used to store some information. Variables can store numbers or text among other things. We use the var keyword and then specify the name of the variable – this variable’s name is playerImage and will store the link to the image which we will use for the character. Variable names can’t contain spaces and must begin with a lowercase letter – these are part of the rules of the JavaScript language.

There are rules that you must follow in programming language such as ending a statement/line with a semi-colon, using certain brackets, and correctly spelling keywords used in a language, for example, var and if. These rules are known as the programming language syntax. Because the image link is stored in a variable, whenever we want to use the image we just have to refer to the variable by its name rather than having to type in the long link every single time.

Step 6

At this point you should have a backdrop and specified the image for the player’s character in the game. You won’t be able to see the player sprite yet because we haven’t specified how big it should be and where it should be placed on the screen. To do that, you need to add the following code:

 

var player = new Image({
  url: playerImage,
  width: 32,
  height: 32,
  x: 0,
  y: 0
})

In the code above, we create a variable called player and use the image from the playerImage variable to represent the player character. We then specify the width and height of the player. Lastly, we specify the x and y position of the player on the screen (x is horizontal axis across screen, y is vertical axis). Hint: x: 0, y: 0 is the centre of the screen.

This is what you should now see on your screen:

woof_step5

Step 7

Now that we have the player in your game, we can add an enemy to chase after (a not-so-scary monster). We will firstly specify the image sprite to use for the enemy and then we will create the enemy object in the game specifying its sprite url, width, height, and initial position on the screen (x and y axes). We will make the x position of the enemy 60 so that it is next to the player (and not on top of it). To do this, add the following code:

var enemyImage = 'http://www.codemahal.com/sprites/enemy.png';
var enemy = new Image({
  url: enemyImage,
  width: 32,
  height: 32,
  x: 60,
  y: 0
})

This is what your game should now look like with the player and enemy next to each other in front of a grass backdrop:

woof_step7

Step 8

The next step is to make the player move! To do this, we need to check which keys on the keyboard are being pressed. We can use the up and down arrows on the keyboard to move the player up and down. We can also use the left and right keys on the keyboard to move the player left and right. Rather than just checking if a key has been pressed, we can check if keys are currently being pressed.

We can use a forever loop to keep checking if keys are being pressed. We can also use includes to check if multiple keys are being pressed at the same time instead of just checking one key at a time.

Create a forever loop and inside that forever loop you can add if statements that check if a key is being pressed and then move the player on the x or y axis in the direction according to the key that is being pressed.

woof_step8a

woof_step8b

Here is the code you need to add which will make the player move 5 spaces in the direction of the arrow key that is pressed on the keyboard:

forever(() => {
  if (keysDown.includes('LEFT')) {
    player.x -= 5
  }

  if (keysDown.includes('RIGHT')) {
    player.x += 5
  }

  if (keysDown.includes('UP')) {
    player.y += 5
  }

  if (keysDown.includes('DOWN')) {
    player.y -= 5
  }  
})

Your code and game should now look like this. If you click in the game preview window you can use the left, right, up, and down keys to move your character around!

woof_step8c

Tip: You can find different pieces of code to use for movement by clicking on Motion. You can use different pieces of code for control (eg. check if a condition is true, or repeat instructions) by clicking on Control. You can also find code for checking keypresses by clicking on Sensing.

Step 9

Now that we have a player and an enemy, we will need to allow them to interact. The aim of this game will be to catch as many enemies as possible in 20 seconds. When you catch an enemy another one will appear in a random location. A timer counts down from 20 seconds and the score is counted and displayed on screen.

Before we allow the player to catch an enemy, we will add text on screen to display the score, countdown timer, ‘Game over’ message, and ‘Press P to play again’ message that displays at the end of the game.

To add text on screen, you need to create a variable that will store the different text properties including the actual text displayed, font size, colour, font family, alignment, and x and positions on the screen.

Add the following code between the code you added to create the enemy sprite and the forever loop:

var scoreText = new Text({
  text: () => "Score: 0",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: minX + 20,
  y: maxY - 20
})

var timerText = new Text({
  text: () => "Time remaining: 20",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: maxX - 160,
  y: maxY - 20
})

var gameOverText = new Text({
  text: () => "GAME OVER!",
  size: 40,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 60
})

var playAgainText = new Text({
  text: () => "Press P to play again",
  size: 20,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 0
})

Your game should now look like this:

woof_step9

Step 10

Now we need to set the score to be 0 at the beginning of the game and set the timer to 20 at the beginning of the game (as the counter will count down from 20 to 0 seconds). Create a new variable called score and give it a value of 0. Then create a variable called time and give it a value of 0. We also don’t want the ‘Game over’ message or ‘Press P to play again’ message to display until after the game ends, so we will set these text objects to be hidden using the .hide() function. To do this, add the following code after the code you just added for the on-screen text:

var score = 0;
var time = 20;
gameOverText.hide()
playAgainText.hide()

After adding this code, you should now see that the ‘Game over’ and ‘Press P to play again’ text.

woof_step10

Step 11

Next, we can add the countdown timer functionality. We can use the every function to specify that every 1 second during the game we want the time variable to go down by 1 (the time variable will start at 20 at the beginning of the game and go down by 1 until it reaches 0 and the game ends). Every second the timer will also be updated on screen.

We can add the code if(time !== 0) so the timer won’t under 0 (into negative). !== is an a example of a comparison operator which means “is not equal to”. In other words, the game will only keep counting down if there is time left and once the time variable becomes 0 it will stop counting down. To implement the countdown timer, add the following code after the code that was just added in the previous step:

every(1, "seconds", () => {
  if (time !== 0) {
    time = time - 1;
    timerText.text = "Time remaining: " + time
  }
})

Once you have added this code you should see the timer start to count down and then stop once it reaches 0. This is what the game and code should look like so far:

woof_step11a

woof_step11b

Step 12

Now that we have a working countdown timer we can go ahead and add the ability to score points and make the enemy respawn in random locations on the screen.

Every time the player touches the enemy, the score variable will increase by 1 and the score text will be updated on screen. The enemy will then be moved to a random x and y position on the screen. minX is the minimum x position on screen (left edge of screen) and maxX is the maximum x position on screen (right edge of screen). minY is the minimum y position on screen (bottom edge of screen) and maxY is the maximum y position on screen (top edge of screen).

The enemy will respawn in random positions between those points. Note that in the code below we have the line enemy.y = random(minY, maxY – 30) which will place the enemy at a random y position on screen but 30 spaces below the top of the screen. This ensures that the enemy doesn’t respawn behind the score or time remaining text.

Add the following code inside the forever loop just below the code we added to make the player move using the arrow keys:

if (player.touching(enemy)) {
    score = score + 1;
    scoreText.text = "Score: " + score;
    enemy.x = random(minX, maxX)
    enemy.y = random(minY, maxY - 30)
  }

After adding this code as shown below, you will be able to collect points every time you catch the enemy. You can also improve this code by making sure the enemy doesn’t respawn too close to the edge of the screen where it might be partially hidden. You could also randomly respawn the player for extra challenge.

woof_step12

Step 13

Once the time has reached 0 we won’t want the player to keep moving around and collecting more points (they will have to start a new game). So we can say that if(time === 0) (which means “if time is equal to 0”), set the player and enemy sprites to be hidden and show the ‘Game over’ text and ‘Press P to play again’ text on screen. Add the following code after the code you added in the previous step (inside the forever loop).

if(time===0){
    player.hide()
    enemy.hide()
    gameOverText.show()
    playAgainText.show()
  }

woof_step13

Step 14

Lastly, we can check if the P key has been pressed on the keyboard and if so, set the score back to 0 and timer back to 20, show the player and enemy sprites on screen, reset the timer and score text on screen, and hide the ‘Game over’ and ‘Press P to play again’ text on screen. Add the following code inside the forever loop just below the code added in the previous step:

if (keysDown.includes('P')) {
    score = 0
    time = 20
    player.show()
    enemy.show()
    scoreText.text = "Score: 0";
    timerText.text = "Time remaining: 20";
    gameOverText.hide()
    playAgainText.hide()
  }

woof_step14

And that’s it! You have just completed building your first game in WoofJS using JavaScript code. Make sure you click on Save to keep your work.

woof_step14b

Questions

1. What do the following key terms mean? Can you give an example for each?

  • Syntax
  • Variable
  • Conditional statement
  • Loop
  • Function
  • URL

2. What is the JavaScript programming language used for. Provide three examples of apps or games you can find that were built using the JavaScript language.

3. Two main types of errors you might encounter when coding are logic errors and syntax errors. Explain the difference between these two different types of errors.

Tips

  • If you receive error messages or your code isn’t working, make sure you have closed brackets and quotes where necessary (or don’t have too many brackets or quotes), and make sure the brackets and quotes are matching
  • Save frequently so you don’t lose your hard work if the Internet drops out or your computer crashes
  • Look at all the different blocks for different pieces of code you can use – experiment with code and work out different ways of solving problems – it’s the best way to learn coding!

What next?

You could try adding a feature to your game that allows it to save high scores. You could also add hazards to avoid, make the player respawn in random locations, or make the monster move around. Also, try improving the appearance of text on screen by changing font family/style.

Complete code

Here is the complete code for the game:

setBackdropURL('http://www.codemahal.com/sprites/grass_background.png');
var playerImage = 'http://www.codemahal.com/sprites/hero.png';
var player = new Image({
  url: playerImage,
  width: 32,
  height: 32,
  x: 0,
  y: 0
})

var enemyImage = 'http://www.codemahal.com/sprites/enemy.png';
var enemy = new Image({
  url: enemyImage,
  width: 32,
  height: 32,
  x: 60,
  y: 0
})

var scoreText = new Text({
  text: () => "Score: 0",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: minX + 20,
  y: maxY - 20
})

var timerText = new Text({
  text: () => "Time remaining: 20",
  size: 16,
  color: "white",
  fontFamily: "arial",
  textAlign: "left",
  x: maxX - 160,
  y: maxY - 20
})

var gameOverText = new Text({
  text: () => "GAME OVER!",
  size: 40,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 60
})

var playAgainText = new Text({
  text: () => "Press P to play again",
  size: 20,
  color: "white",
  fontFamily: "arial",
  textAlign: "center",
  x: 0,
  y: 0
})

var score = 0;
var time = 20;
gameOverText.hide()
playAgainText.hide()

every(1, "seconds", () => {
  if (time !== 0) {
    time = time - 1;
    timerText.text = "Time remaining: " + time
  }
})

forever(() => {
  if (keysDown.includes('LEFT')) {
    player.x -= 5
  }

  if (keysDown.includes('RIGHT')) {
    player.x += 5
  }

  if (keysDown.includes('UP')) {
    player.y += 5
  }

  if (keysDown.includes('DOWN')) {
    player.y -= 5
  } 
  
    if (player.touching(enemy)) {
    score = score + 1;
    scoreText.text = "Score: " + score;
    enemy.x = random(minX, maxX)
    enemy.y = random(minY, maxY - 30)
  }
  
    if(time===0){
    player.hide()
    enemy.hide()
    gameOverText.show()
    playAgainText.show()
  }
  
    if (keysDown.includes('P')) {
    score = 0
    time = 20
    player.show()
    enemy.show()
    scoreText.text = "Score: 0";
    timerText.text = "Time remaining: 20";
    gameOverText.hide()
    playAgainText.hide()
  }
  
})

JavaScript quiz tutorial

This tutorial explains how to create a quiz program in the JavaScript language which will look like this (you can change the theme):

quiz

The quiz will look like this when the user has finished it:

quiz_complete

By following this tutorial you will develop the following programming skills:

Please follow the steps below. You can download the complete code at the bottom of this page, but make sure you read the steps so you know what each part of the code is responsible for.

Setting up the HTML code

To begin, create a new html file eg. quiz.html in a coding text editor. You need to add some HTML code in the body section of an html file which will create a heading (in this example it is a h2 size heading) with an id of ‘test_status‘ and a div with an id of ‘test‘. The test_status heading will display the status of the quiz eg. “Question 2 of 4”, or “Test completed”. The ‘test’ div will display the actual questions and possible answers in the quiz. Use the code below to get started.

<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>

</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>

</html>

Now that you have a heading a a div in your HTML code, it is time to apply a style to them by adding some CSS code. In the head section of the HTML file, under the title tags, add the following code:

<style>
div#test{ border:#5AB029 3px solid; padding:10px 40px 40px 40px; background-color:#E5FCE3; width:50%;}
</style>

You can change the code above by changing the border or background colours, border thickness and padding, or adding extra style properties.

Setting up the JavaScript code

Inside the head section of the HTML code under your </style> tag, add the following code:

<script type="text/javascript">
var pos = 0;
var correct = 0;
var test, test_status, question, choice, choices, chA, chB, chC;
</script>

The code above will create several variables. Firstly, the pos variable is used to record what the position the user is at in the test eg. question 3 out of 4. The correct variable stores the number of questions answered correctly. The test variable contains the ‘test’ div and the test_status variable is used to contain the ‘test_status’ heading which displays the user’s progress in the test.

The question variable will contain a question grabbed from an array, the choice variable will contain the user’s selected answer for a question, choices variable will contain the possible answers that will be displayed to the user, and chA, chB, and chC variables will contain each possible answer (A, B, or C) in the multiple choice quiz.

Adding the questions, possible answers, and answer key to the quiz

Now the questions need to be created along with their possible answers and the correct answer (answer key). In this example, we will have four questions (you can add more) with three multiple choice options for each question (A, B or C). To do this, we make a multidimensional array which contains the questions, the options for each question, and the answer key for each question. Add the code below and change the questions to your liking.

This code goes inside the script tags under the variables you created in the previous step.

var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];

Create the get function

This quiz needs to get elements from the web page (the heading and the div) and then modify those elements several times. Rather than constantly typing the document.getElementById(); method over and over again, we can simply turn it into a function called get. Add this code inside the script tags after the array you made in the previous step.

function get(x){
  return document.getElementById(x);
}

Create the renderQuestion function

The renderQuestion function will be used to get the ‘test‘ div, check the user’s position in the quiz, and if they have not yet completed the quiz then they will be served different questions. The function will display the user’s progress and the actual question and options to the user. The user must choose an answer by selecting a radio button next to an answer and then click the ‘Submit Answer’ button.

Add this code inside the script tags below the get function you created in the previous step.

function renderQuestion(){
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;
  }
  get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}

Create the checkAnswer function

The checkAnswer function is used to, you guessed it…check the answer. While the quiz is incomplete, each user choice will be checked and compared with the correct answer associated with each question (stored in the questions array). At the end of this question being called, the renderQuestion will be called.

Add the code below inside your script tags under the renderQuestion function you created in the previous step.

function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[pos][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
  pos++;
  // then the renderQuestion function runs again to go to next question
  renderQuestion();
}

Get the quiz to load

The last step involves adding one line of code that will run the renderQuestion function as soon as the page has loaded (using an event listener that checks for a load event). When that function is loaded, the questions will be presented to the user and the quiz will begin.

Add the code below inside your script tags in your code. Add it below the checkAnswer function you created in the previous step. make sure you have ended the script section by closing it with the </script> tag!

window.addEventListener("load", renderQuestion, false);

And that’s it! You have now created a JavaScript quiz game. Challenge yourself by trying to add the following features to your quiz:

  • Add more questions (easy!)
  • Change the quiz theme (background colours/gradient, border, font style, etc)
  • Tell the user which questions they answered incorrectly
  • Display a visual progress bar during the test
  • Display the user’s score as a percentage value
  • Allow the user to re-take the quiz
  • Add more possible answers (eg. A, B, C, D)
  • Store the results in a database using PHP/MySQL (tricky)

Complete code

Here is the complete JavaScript code for the quiz program:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>

<style>
div#test{ border:#5AB029 3px solid; padding:10px 40px 40px 40px; background-color:#E5FCE3; width:50%;}
</style>

<script type="text/javascript">
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
// this is a multidimensional array with 4 inner array elements with 5 elements inside them
// if you don't want answers viewable in the code, then you should use PHP and mySQL database
var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];
// this get function is short for the getElementById function	
function get(x){
  return document.getElementById(x);
}
function renderQuestion(){
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;
  }
  get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[pos][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
  pos++;
  // then the renderQuestion function runs again to go to next question
  renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>

</html>

Parallax scrolling effect with HTML5, CSS and JavaScript

This tutorial explains how to add a parallax scrolling effect using some simple HTML5, CSS and JavaScript code. If you want to know more about the origins of the parallax effect, click here to see how Disney used the parallax effect in their early cartoon animation.

Click on the image below to see a working demo of the parallax effect created in this tutorial.

Parallax scrolling effect demo.
Parallax scrolling effect demo.

Watch the video below and then scroll down to see the sample code and sample image files you can use.

Sample code and images

Click on the image thumbnails below to download the sample background image and two parallax layer div background images.

background
background.png
parallax
parallax.png
parallax2
parallax2.png

All of the HTML, CSS and JavaScript code for this demo is included in one HTML file. You can copy the code from below – please note that I have included several of the same paragraphs in the code so that there is plenty of text content on the page to allow the user to scroll in order for the parallax effect to be visible.

<html>
<head>
  <title>Parallax effect</title>

  <style type="text/css">
    body{
      margin:0px;
      background:url(background.png) fixed;
    }
    #parallax_layer1{
      position:fixed;
      background:url(parallax.png) no-repeat 0px 300px;
      width:100%;
      height:800px;
    }
    #parallax_layer2{
      position:fixed;
      background:url(parallax2.png) no-repeat 0px 500px;
      width:100%;
      height:1000px;
    }
    #content_layer{
      color:#F9A7B0;
      background-color:black;
      opacity:0.5;
      font-family:Arial;
      position:absolute;
      padding:10px 10px 10px 30px;
      width:40%;
      right:0px;
    }
  </style>

  <script>
  // Create the parallax function.
  function parallax(){
    var parallax_layer1 = document.getElementById('parallax_layer1');
    var parallax_layer2 = document.getElementById('parallax_layer2');
    // Dividing the pageYOffset by a positive number will slow down the parallax effect.
    // Adding a '-' before (window.pageYOffset) makes the parallax
    // layer move up instead of down when scrolling.
    parallax_layer1.style.top = -(window.pageYOffset/2)+'px';
    parallax_layer2.style.top = -(window.pageYOffset/6)+'px';
  }
  // Add an event listener which will detect scrolling and run
  // the parallax function.
  window.addEventListener("scroll",parallax);

  </script>

</head>
<body>
  <div id="parallax_layer1"></div>
  <div id="parallax_layer2"></div>
  <div id="content_layer">
    <h1>Parallax effect</h1>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>

    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
    <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>

  </div>	
</body>
</html>

Controlling audio with scripts

This tutorial explains how to control the audio in your game using scripts. You can play, stop, pause and resume sound effects and songs in your game when certain events occur by controlling the sound with code. This video explains how to do that and if you scroll down you will find the sample code.

The following sample code is used to control an audio source/slot called “song” that is attached to the same entity that the script is attached to. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                this.entity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                this.entity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

The following sample code is used to control an audio source/slot called “song” that is attached to a Sound entity called “mySound“. The script can be attached to any other entity in the game scene. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // creates variable for audio entity
            var AudioEntity = app.root.findByName('mySound');
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                AudioEntity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                AudioEntity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

Make a 3D object move with code in PlayCanvas

In this tutorial we will start writing our very lines of JavaScript code in the PlayCanvas code editor! To start with, we will make a 3D object (eg. a box or sphere) move around the screen on its own. Watch the video below and then scroll down to see the sample code and try it out for yourself.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script. Launch your game and then watch the object start moving to the right (if your object moves to the left, then your camera is on the opposite side of the object). Try changing the x, y, and z translateLocal parameters to make your object move in different directions at different speeds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 this.entity.translateLocal(0.01,0,0);
 }
 };
 
 return Move;
});

An overview of scripts in PlayCanvas

This tutorial will not show how to write code in PlayCanvas just yet, but will give you an overview of how scripts work in PlayCanvas and the structure of a basic script. It is important to watch this tutorial first especially if you don’t have any coding experience in JavaScript. The next tutorial will show you how to start writing your JavaScript code for your games.

Here is the sample code from the tutorial (it is just a template and doesn’t actually make your game do anything):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pc.script.create('test', function (app) {
 // Creates a new Test instance
 var Test = function (entity) {
 this.entity = entity;
 };
 
 Test.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 }
 };
 
 return Test;
});

Drawing quadratic curves

This tutorial explains how to draw quadratic curves on the HTML canvas. We can use the quadraticCurveTo() method to draw a quadratic curve on the canvas.

The quadratic curve is defined by three things: the context point, the control point, and the ending point. These curves can also be styled using the lineWidth, stroke style and lineCap properties just like regular lines.

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Quadratic curves</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(50,50);
 ctx.lineTo(300,50);
 ctx.quadraticCurveTo(300,100,350,100); // (control point x, control point y, x, y)
 ctx.lineTo(350,200);
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Drawing arcs using the arcTo method

This tutorial explains how to draw arcs using the arcTo method. You will learn how to draw arcs and join arcs to other lines on the canvas.

This is what the arc attached to lines will look like:

Screen Shot 2015-05-08 at 6.56.39 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>The arcTo method</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.moveTo(50,50);
 ctx.lineTo(200,50);
 ctx.arcTo(250,50,250,100,50); // x1, y1, x2, y2, radius
 ctx.lineTo(250,200);
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Drawing quadratic curves

Clipping shapes on the canvas

This tutorial will explain how to clip shapes on the canvas. The clipped shape example in the video will look like this:

Screen Shot 2015-05-08 at 7.01.35 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Clipping shapes</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.rect(50, 50, 100, 100) // x, y, width, height
 // we will clip one rectangle with the other 
 ctx.clip();
 ctx.rect(0, 0, 100, 100)
 ctx.stroke();
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="200" height="200">
</body>
</html>

Next tutorial: Drawing arcs and circles on the canvas

Drawing paths on the canvas

This tutorial explains how to draw paths on the canvas. Paths can be used to build shapes by creating lines, filling the path, and filling the background with a colour, as seen in the example below.

Screen Shot 2017-04-14 at 5.06.13 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Drawing paths</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.beginPath(); // this will reset the current default path
 ctx.moveTo(50,50); // x, y coordinates of start of line
 ctx.lineTo(250,50); // creates new line to these x, y coordinates
 ctx.lineTo(250,150); // creates another line to these x, y coordinates
 ctx.lineTo(50,150);
 ctx.fill();
 ctx.closePath(); // this will close the path to complete the rectangle (adds the last line on the left side of rectangle)
 ctx.stroke(); // strokes the current path
 alert(ctx.isPointInPath(75,75)); // returns a true/false value indicating whether the specified point is within a path
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Clipping shapes on the canvas

Joining lines on the canvas

This tutorial explains how to join lines on the canvas. The lines that we will join in this tutorial will end up looking like this:

Screen Shot 2015-05-08 at 6.59.43 pm

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>Joining lines</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.lineWidth = 20;
 ctx.lineCap = "butt"; // options are: square, round, butt
 ctx.lineJoin = "round"; // options are: round, bevel, miter
 //ctx.miterLimit = 3;
 //ctx.setLineDash([20,10]); //adds dashes -length of dash,length of gap between dash
 //ctx.lineDashOffset = 20;
 
 ctx.beginPath();
 ctx.moveTo(50,50);
 ctx.lineTo(150,250);
 ctx.lineTo(250,50);
 ctx.lineTo(150,50);
 ctx.strokeStyle="#FF0000";
 ctx.stroke();
 //ctx.fill(); will add a fill
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="300" height="300">
</body>
</html>

Next tutorial: Drawing paths on the canvas

Using colour gradients and patterns

The code below shows how to use linear and radial gradients to fill rectangle shapes.

The three shapes will look like this (linear gradient on top left, radial gradient on top right, image pattern on bottom left side):

Screen Shot 2015-05-08 at 6.53.39 pm

Watch the video below and then scroll down to see the sample code.

Here is the code:

<!DOCTYPE html>
<html>
<head>
 <title>Gradients and patterns</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
 <script>
 var patternImage = new Image();
 patternImage.src = "pattern.png";
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 var gradient = ctx.createLinearGradient(0,0,150,0); // x1, y1, x2, y2 
 gradient.addColorStop(0, "red");
 gradient.addColorStop(0.5, "yellow");
 gradient.addColorStop(1, "green");
 ctx.fillStyle = gradient;
 ctx.strokeStyle = "blue";
 ctx.fillRect(0,0,150,75);
 ctx.strokeRect(0,0,150,75);
 
 var gradient2 = ctx.createRadialGradient(350,100,0,350,100,200);
 // ctx.createRadialGradient parameters are x1, y1, r1, x2, y2, r2
 gradient2.addColorStop(0, "yellow");
 gradient2.addColorStop(1, "blue");
 ctx.fillStyle = gradient2;
 ctx.strokeStyle = "blue";
 ctx.fillRect(250,0,200,200);
 ctx.strokeRect(250,0,200,200);
 
 var pattern = ctx.createPattern(patternImage, "repeat");
 ctx.fillStyle = pattern;
 ctx.strokeStyle = gradient;
 ctx.lineWidth = 20;
 ctx.fillRect(20,150,200,200);
 ctx.strokeRect(20,150,200,200);
 }
 window.onload=draw;
 </script>
</head>
<body>
 <canvas id="myCanvas" width="500" height="400">
</body>
</html>

Next tutorial: Simple animations using JavaScript

Introduction to JSON

JSON stands for JavaScript Object Notation. JSON is a light-weight data interchange format that uses JavaScript syntax in text format that can be read and used as data by other programming languages.

In this example, we will use JSON to define an object with an array of records – we will use the Avengers characters for this example. Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>JSON</title>
</head>
 
<body>
<h2>The Avengers</h2>
 
<p id="avengerstext"></p>
 
<script>
var text='{"avengers":['+
'{"firstName":"Bruce","lastName":"Banner"},'+
'{"firstName":"Tony","lastName":"Stark"},'+
'{"firstName":"Natalia","lastName":"Romanova"},'+
'{"firstName":"Thor","lastName":"Odinson"}]}';
 
obj = JSON.parse(text);
document.getElementById("avengerstext").innerHTML=obj.avengers[0].firstName+" "+obj.avengers[0].lastName+"<br>"+obj.avengers[1].firstName+" "+obj.avengers[1].lastName+"<br>"+obj.avengers[2].firstName+" "+obj.avengers[2].lastName+"<br>"+obj.avengers[3].firstName+" "+obj.avengers[3].lastName;
 
</script>
 
</body>
</html>