Tag Archives: code

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

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

Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. There is no need to use a counter, specify an increment, or a condition. The foreach loop will simply loop through every element in the array.

Foreach loops are written in a way that is easy to understand, for example:

foreach (string item in itemsList){
   Console.WriteLine(item);
}

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

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods

Arrays in C#

Arrays are basically a list of items of the same type that are grouped together in a single container. Unlike variables which can only contain one value at a time, arrays can contain many different values of the same type (eg. string, or integer). This tutorial explains how to create arrays, access elements in an array, and use for loops to work through the elements in arrays.

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

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};
      // Create an array of int type
      int[] ages = {26,18,49,33};
      // Display second item in names array (array indexing starts at 0)
      Console.WriteLine(names[1]);
      // Display fourth item in ages array
      Console.WriteLine(ages[3]);
      // Store the names array's length (number of elements in array) in variable
      int arrayLength = names.Length;
      // Display names array's length
      Console.WriteLine(arrayLength);
      // Go through each element in names array and check if Sam exists in array
      for (int i = 0; i < arrayLength; i++) {
        if (names[i] == "Sam") {
          Console.WriteLine("Sam is here!");
        }
      }
    }
  }
}

Next tutorial: Foreach loops in C#

Do while loops in C#

A do while loop is a type of loop which repeats code while a certain condition evaluates to true. However, unlike a while loop which tests the condition first, a do while loop tests the condition after running instructions inside the loop. This means that the code inside the loop will always run at least once even if the condition evaluates to false. This is an example of post-test repetition.

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

Sample code

Take a look at the sample code below. The counter is set to 99 and the condition being tested is counter < 10. However, the code inside the loop runs the first time even though the condition evaluates to false because a do while loop runs the code inside the loop before testing the condition (meaning that the instructions inside the loop will always run at least once).

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 99;
      do
      {
        Console.WriteLine("Counter is: " + counter);
        counter++;
      } while(counter < 10);
      Console.ReadLine();
    }
  }

}

Next tutorial: Arrays in C#

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 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

Data types in Java

A data type classifies various types of data eg. String, integer, float, boolean, the types of accepted values for that data type, operations that can be performed on the data type, the meaning of the data, and the way that data of that type can be stored.

The table below shows the most commonly used data types used in the Java programming language.

Type Description Example
int The integer (int) data type stores positive or negative whole number values. 20
float The float data type stores floating point numbers (numbers with decimal places) eg. 43.65 . Often, you will need to end a float value with an ‘f’ character eg. 43.65f 43.65f
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is always surrounded by single quotes eg. ‘a’. ‘a’
String The String data type stores letters, numbers and other characters in the form of words or sentences. A string value is always surrounded by double quotes eg. “Hello World”. “Hello world”
boolean The boolean data type stores true or false values only eg. true true

The table below shows some of the other data types used in the Java programming language.

Type Description Example
byte The byte data type stores integer numbers ranging from -128 to +127 118
short The short data type is used for integer numbers ranging from -32,768 to +32,767 -28,471
long The long data type is used for integer values exceeding 2.14 billion ‘a’
double The double data type is used for extremely long floating point numbers 1.7976931348623157 × 10^308

Sample code

The sample Java code below shows how some of the different data types can be stored in variables. Later on, we will look at how to actually work with the values of different data types (eg. math calculations with integers and floats, and decision making with booleans).

The code includes comments explaining each data type.

package myjavaproject;

public class DataTypes {
    public static void main (String[] args){
        String message = "Hello"; // variable of String data type
        char letter = 'a'; // variable of char data type
        int number = 20; // variabe of int (integer) data type
        float decimal = 43.65f; // variable of float (floating point) data type
        boolean result = true; // variable of Boolean data type
        
        // now let's output the values of the different variables
        System.out.println("Message is " + message);
        System.out.println("Letter is " + letter);
        System.out.println("Age is " + number);
        System.out.println("Score is " + decimal);
        System.out.println("The answer is " + result);
    }
}

Variables in Java

In this tutorial you will learn how to create variables in the Java programming language. Variables are used to store data in a program.  A variable is like a ‘container’ that can store a value that can be used within the program. These values can be accessed, used and modified throughout the code.

Examples of values that you might need to store in a program include the score in a game, the user’s name, a password, or numbers used in calculations. Variables can store values of different data types – we’ll look at these in the next tutorial.

Variables have three important properties:

  • Variable name (identifier) – the actual name of the variable eg. score, username, age, price. Each variable must have a unique name. Some variable names can’t be used if they are the same as a reserved word used elsewhere in the language for other things such as a function. Variable names often cannot contain spaces or start with digits (rules vary in different languages)
  • Data type – the type of data that the variable will be storing such as text or numbers. There are special names for different data types that we will look at in the next tutorial
  • Value – the actual information being stored in the variable such a “Bob” for a variable called firstName or 26 for a variable called age.

The example below shows a new variable called message being created in the Java language. The variable is of the String data type (text that can contain letters, numbers and different characters) and is given an initial value of “Hello“.

java_variables

When you create a variable in a program you declare the variable. This means you give it a name and specify the data type. You may decide to not give it a value at that point in the program and give it a value later on, or you may decide to initialise the variable with a value (that can also be changed later). In the example above, the variable is declared and given an initial value all in one line of code.

Sample code

The sample code below shows a variable called ‘message’ being declared and given a value of “Hello”. The value is displayed on the screen to the user. Then, the value is changed to “Hello there” and this is displayed as output on the screen. Lastly, the message is displayed and the text “friend.” is added on the end when displayed as output so that the message being displayed is “Hello there friend.”. This is an example of concatenation (a fancy word for joining) where two strings are joined together.

You might notice that some lines of code that begin with two // forward slashes. These are comments in the code explaining what is going on. Comments are not carried out as instructions in the code but are used to annotate your code with explanations of what the code is meant to do, or you can also use them to add information about the author of the code, the program’s purpose or when it was created/modified.

package myjavaproject;

public class CreatingVariables {
    public static void main (String[] args){
        String message = "Hello"; // create and initialise String variable
        System.out.println(message);  // output variable value
        message = "Hello there"; // modify variable value
        System.out.println(message); // output modified variable value
        System.out.println(message + " friend.");  // concatenate strings
    }
}

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