# Arithmetic and assignment operators in C#

#### Operators

Operators are symbols that are used to perform operations on data. The range of different operations you can perform can usually be placed in these four categories:

• Arithmetic operators
• Assignment operators
• Equality operators
• Logical operators

In this tutorial we will look at arithmetic and assignment operators used in the C# language. Later on in these tutorials we will also look at equality and logical operators when we work with conditional statements.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used on number variables eg. int and float (although they can be used for other things too eg. the  + operator can be used to join two strings together).

 Operator Name / description + Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together. – Subtraction – this operator is used to subtract one number from another. * Multiplication – this operator is used to multiply two numbers together. / Division – this operator is used to divide one number by another. % Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

`<variable name> <assignment operator> <value>;`

For example: x = 5; (or int x = 5; if the variable’s type has not already been declared).

The table below shows the different assignment operators available in C#.

 Operator Description = The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign. += , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5. ++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Watch the video below to see how arithmetic and assignment operators are used in the C# language and then scroll down for the sample code.

#### Sample code

```using System;

namespace MyCSharpProject
{
class MainClass
{
public static void Main(string[] args)
{
string message = "The result is ";
float num1 = 6f;
float num2 = 4f;

float result = num1 + num2 + 10f;

result = num1 - num2;
result = num1 * num2;
result = num1 / num2;
result = num1 % num2;

int num3 = 30;
num3--;

Console.WriteLine(result);
Console.WriteLine(num3);
}
}
}```

# Variables, constants and data types in C#

In this tutorial you will learn about variables, constants and data types in the C# language.

Variables are like containers that can store data that you will use in your application. Variables can be given a value to store that can be accessed and modified or updated throughout the program whereas constants are given a value that can’t be changed in another part of the program – in other words the variable’s value is constant throughout the program.

Variables and constants must be given a unique name (starting with lowercase letter and cannot contain spaces or special characters) and they must have a certain type. A type specifies the kind of data that a variable can hold. A variable that has a name and a type can then have a value assigned to it.

Take a look at the following line of code:

`int myNumber = 5;`

The line of code above says that a new variable called myNumber is being declared. It is of the int (integer) type and is assigned a value of 5.

The table below shows the data types available in the C# language.

 Type Description int The integer data type stores positive or negative whole numbers eg. 5 float The float data type stores floating point numbers (numbers with decimal places). double The double data type stores floating point numbers but with double precision. bool The bool (short for Boolean) data type stores true or false values only eg. true 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 written in single quotes eg. ‘a’. string The string data type stores letters, numbers and other characters in the form of words or sentences. A string value is written inside double quotes eg. “Hello World”.

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

#### Sample code

```using System;

namespace MyCSharpProject
{
class MainClass
{
public static void Main(string[] args)
{
const string mySentence = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine(mySentence);

int myNumber = 5;
Console.WriteLine(myNumber);

float myFloat = 15.279f;
Console.WriteLine(myFloat);

double myDouble = 150.24649;
Console.WriteLine(myDouble);

bool myBool = false;

}
}
}```

Next tutorial: Arithmetic and assignment operators

# Introduction to C#

Welcome to the Coding in C# tutorial series. While working through these tutorials you will learn the fundamentals of object-oriented programming and develop the skills to write your own applications using the C# programming language.

C# is a modern, general purpose, object-oriented programming language used to develop desktop applications on both Windows and Mac platforms, mobile apps for iOS, Android and Windows Phone platforms, as well as games for desktop, mobile and even consoles. The aim of this series is not just to teach you the code, but to give you a solid understanding of the object-oriented programming paradigm (covered later in the series).

To get started, you’ll need a programming environment to code in. There are different programs you can use for writing C# code and testing your applications such as

In these tutorials, I will be demonstrating C# coding using Xamarin on MacOS although the steps will be mostly the same using other software on other platforms.

Watch the video below and then scroll down to see the sample code for your first Hello World application in C#.

#### Sample code

```using System;

namespace MyCSharpProject
{
class MainClass
{
public static void Main(string[] args)
{
// This displays "Hello world" message:
Console.WriteLine("Hello world!");
// This stops console from auto-exiting:
}
}
}```

Next tutorial: Variables, constants and data types

# 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"){
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);
}

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

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

# 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“.

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

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

# Moving the player in a 2D game with Unity and C# code

This video explains how to move your player in a 2D game in Unity with C# code. After watching this video, you will be able to move your player left and right in a scene using keyboard input.

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

#### Sample code

```using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float speed = 5f;
private float movement = 0f;
private Rigidbody2D rigidBody;

// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody2D> ();
}

// Update is called once per frame
void Update () {
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);
}
}
}```

Next tutorial: Making the player jump with C# code

# Introduction to C# scripting & collision detection for 2D games in Unity

This video gives an introduction to writing code for 2D games in Unity using the C# programming language. We’ll get started by adding collision detection so that our player object (or character) can collect points when colliding with coins in the game. You’ll learn how to setup 2D collision detection, increase a score variable, display messages in the console to test your code, and how to destroy objects (or make objects disappear) in a scene using code.

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

#### Sample code

```using UnityEngine;
using System.Collections;

public class CoinScript : MonoBehaviour {

public int score = 0;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnTriggerEnter2D(Collider2D other){
Destroy (gameObject);
score++;
Debug.Log ("Score: " + score);
}
}```

Next tutorial: Moving the player with C# code