Tag Archives: development

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()
  }
  
})

Adding collectables and scoring to a 2D game in Unity

This tutorial explains how to add collectables and scoring to a 2D game in Unity. We will use the LevelManager script and CoinScript script from previous tutorials to improve the existing coin counting system, and we will also add more coins with different values. In the next tutorial, we will add a UI to display the number of coins on screen to the user.

Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the CoinScript script.

using UnityEngine;
using System.Collections;

public class CoinScript : MonoBehaviour {
  private LevelManager gameLevelManager;
  public int coinValue;

  // Use this for initialization
  void Start () {
    gameLevelManager = FindObjectOfType<LevelManager> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if(other.tag == "Player"){
      gameLevelManager.AddCoins(coinValue);
      Destroy (gameObject);
    }
  }
}

Here is the sample C# code for the LevelManager script. The score won’t be displayed on screen until we add the UI Text element in the next tutorial.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
  }
}

Next tutorial: Adding a UI to display the score

Adding a UI to display the score in a 2D game with Unity

This tutorial continues on from the previous tutorial on adding collectables and scoring to a 2D Unity game. In the previous tutorial, we improved the points scoring system and added collectables (coins) of different values).

In this tutorial we will add a UI (user interface) which will display the number of coins collected to the user. The LevelManager script will be responsible for displaying and updating the score text on screen. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;
  public Text coinText;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
    coinText.text = "Coins: " + coins;
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
    coinText.text = "Coins: " + coins;
  }
}

Adding a particle system to a 2D game in Unity

In this tutorial we will add a particle system to a 2D game in Unity. Particle systems emit particles in a game and can be used for adding a variety of effects like fire sparks, smoke, rain, and fog. We will use a particle system to emit spark effects.

Watch the video below to see how you can add particle systems to your own 2D game.

Next tutorial: Adding collectables and scoring

Adding a delay to respawn in a 2D Unity game

This tutorial continues on from the previous tutorials on setting up a fall detectoradding checkpoints, adding the ability to respawn the player, and adding a Level Manager to control respawning in a 2D game.

In this tutorial, we will use the Level Manager to control respawns and we will add a delay to respawns. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the PlayerController script.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;
  public Vector3 respawnPoint;
  public LevelManager gameLevelManager;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
    respawnPoint = transform.position;
    gameLevelManager = FindObjectOfType<LevelManager> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      gameLevelManager.Respawn();
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }
}

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

}

Next tutorial: Particle systems in 2D Unity games

Setting up a Level Manager in a 2D Unity game

This tutorial continues on from the previous tutorials on setting up a fall detectoradding checkpoints, and adding the ability to respawn the player in a 2D game.

In this tutorial you will learn how to set up a Level Manager in a 2D platform game in Unity. The Level Manager will be used in the next tutorial to control player respawn and to add a delay to respawning. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script up to the point shown in the video above.

using UnityEngine;
using System.Collections;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    gamePlayer.gameObject.SetActive (false);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }
}

Here is the sample C# code for the PlayerController script up to the point shown in the video above.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;
  public Vector3 respawnPoint;
  public LevelManager gameLevelManager;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
    respawnPoint = transform.position;
    gameLevelManager = FindObjectOfType<LevelManager> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      gameLevelManager.Respawn();
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }
}

Next tutorial: Adding a delay to player respawn

Respawn the player in a 2D Unity game

This tutorial continues on from the previous two tutorials on setting up a fall detector and adding checkpoints to a game. In the previous two tutorials, we set up the game with a fall detector and added checkpoints in the 2D scene. In this tutorial, we will allow the player to respawn at checkpoints in the game when the player falls off a platform or off the map. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the PlayerController script up to the point shown in the video above. This script will be modified in the next tutorial after adding a Level Manager to the game.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;
  public Vector3 respawnPoint;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
    respawnPoint = transform.position;
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      transform.position = respawnPoint;
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }

}

Here is the sample C# code for the CheckpointController script that is attached to each checkpoint to change their flag colour sprite when reached by the player.

using UnityEngine;
using System.Collections;

public class CheckpointController : MonoBehaviour {

  public Sprite redFlag;
  public Sprite greenFlag;
  private SpriteRenderer checkpointSpriteRenderer;
  public bool checkpointReached;

  // Use this for initialization
  void Start () {
    checkpointSpriteRenderer = GetComponent<SpriteRenderer> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "Player") {
      checkpointSpriteRenderer.sprite = greenFlag;
      checkpointReached = true;
    }
  }
}

Next tutorial: Setting up a Level Manager

Adding checkpoints to a 2D Unity game

This tutorial explains how to add checkpoints to a 2D game so that we can respawn the player back to a checkpoint when the player falls off a platform or off the map. This continues on from the previous tutorial on setting up the fall detector and will be completed when we add the ability to respawn in the next tutorial.

Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the CheckpointController script.

using UnityEngine;
using System.Collections;

public class CheckpointController : MonoBehaviour {

  public Sprite redFlag;
  public Sprite greenFlag;
  private SpriteRenderer checkpointSpriteRenderer;
  public bool checkpointReached;

  // Use this for initialization
  void Start () {
    checkpointSpriteRenderer = GetComponent<SpriteRenderer> ();
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "Player") {
      checkpointSpriteRenderer.sprite = greenFlag;
      checkpointReached = true;
    }
  }
}

Next tutorial: Respawn the player

Setting up a fall detector in a Unity 2D game

This tutorial explains how to set up a fall detector in a Unity 2D game that detects when the player has fallen off a platform or off the map and respawns the player back to a checkpoint. This will be covered across three tutorials. We will look at how to add checkpoints in the next tutorial.

Sample code

Here is the sample C# code for the PlayerController script up to the point shown in the above video. This script will be completed in the next two tutorials.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }

  void OnTriggerEnter2D(Collider2D other){
    if (other.tag == "FallDetector") {
      // what will happen when the player enters the fall detector code (this will be added later)
    }
    if (other.tag == "Checkpoint") {
      respawnPoint = other.transform.position;
    }
  }

}

Next tutorial: Adding checkpoints in the game

Stopping the player from sticking to the edge of platforms and walls in a 2D Unity game

This tutorial will show you a quick fix for stopping the player from sticking to the edge of platforms and walls in your 2D Unity game.

Next tutorial: Setting up a fall detector

Making the camera follow the player in a 2D Unity game with code

This tutorial will show you how to write a script in C# code that will make the camera follow the player in a 2D Unity game. Watch the video below and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

  public GameObject player;
  public float offset;
  private Vector3 playerPosition;
  public float offsetSmoothing;

  // Use this for initialization
  void Start () {
  
  }
  
  // Update is called once per frame
  void Update () {
    playerPosition = new Vector3 (player.transform.position.x, transform.position.y, transform.position.z);
    if (player.transform.localScale.x > 0f) {
      playerPosition = new Vector3 (playerPosition.x + offset, playerPosition.y, playerPosition.z);
    }
    else {
      playerPosition = new Vector3(playerPosition.x - offset, playerPosition.y, playerPosition.z);
    }

    transform.position = Vector3.Lerp (transform.position, playerPosition, offsetSmoothing * Time.deltaTime);
  }
}

Next tutorial: Stopping the player from sticking to the edge of platforms and walls

Flipping the player with code in a 2D Unity game

This tutorial will show you how to flip your 2D game’s player sprite in Unity with C# code so that the player can turn and face the direction in which it is running, walking, or jumping.

Watch the video and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(0.1483552f,0.1483552f);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
      transform.localScale = new Vector2(-0.1483552f,0.1483552f);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }
}

Next tutorial: Making the camera follow the player with code

Controlling 2D player animations with C# code in Unity

In this tutorial, you will learn how to control player animations in your 2D game with C# code in Unity. Watch the video below and then scroll down for the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;
  public Transform groundCheckPoint;
  public float groundCheckRadius;
  public LayerMask groundLayer;
  private bool isTouchingGround;
  private Animator playerAnimation;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
    playerAnimation = GetComponent<Animator> ();
  }
  
  // Update is called once per frame
  void Update () {
    isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer);
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump") && isTouchingGround){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }

    playerAnimation.SetFloat ("Speed", Mathf.Abs (rigidBody.velocity.x));
    playerAnimation.SetBool ("OnGround", isTouchingGround);
  }
}

Next tutorial:  Flipping the player with code