Tag Archives: player

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

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

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

Creating animations for the player sprite in a 2D Unity game

In this tutorial, you will learn how to create idle, walk/run, and jump animations for your 2D player in Unity. In the next tutorial we will set up the player animation controller.

Next tutorial: Setting up the player animation controller

Jumping in a 2D game with ground check in Unity

In this tutorial, you will learn how to write a script in C# code that allows your player to jump only when they are touching the ground.

Watch the video below and scroll down to view 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;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
  }
  
  // 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);
    }
  }
}

Next tutorial: Changing the player sprite

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

In this tutorial you will learn how to write a script to make your player jump in a 2D game with C# code in Unity. In the following tutorial, you will learn how to make the player jump only when they are touching the ground.

Watch the video below and scroll down to view 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;

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

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

Next tutorial:  Jumping with ground check

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

Moving objects with keyboard input in PlayCanvas

If you watched the previous tutorial you would have learned how to make an object move on its own using JavaScript code. In this tutorial, we will make an object move around using keyboard input. That is, if the left arrow key is pressed on the keyboard then we can make the object move left. If the right arrow key is pressed on the keyboard then we can make the object move right, and so on…

Keyboard input will be very useful in your games eg. to make a player jump, to move around, pick up objects or enter your name in the high score book! Watch the video to find out how to add keyboard input to your games and then try out the sample code further down the page.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script.

In the code, you will see app.keyboard.isPressed – this will check if the key is being pressed during the current frame. If you hold down the key, the object will keep moving. If you use another method called app.keyboard.wasPressed instead it will only check if the key was pressed in the current frame (it will detect one keypress and won’t keep the object moving when you hold the key down).

pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 if(app.keyboard.isPressed(pc.input.KEY_RIGHT)){
 this.entity.translateLocal(0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_LEFT)){
 this.entity.translateLocal(-0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_UP)){
 this.entity.translateLocal(0,0.1,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_DOWN)){
 this.entity.translateLocal(0,-0.1,0);
 }
 }
 };
 
 return Move;
});

Mouse input in Unity

This tutorial explains how to detect mouse button clicks and mouse movement in your game using a C# script. This will allow your players to interact with the game using their mouse.

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

Mouse button clicks

To detect mouse button clicks, you use the GetMouseButtonDown() method which takes an integer value (between 0 and 2) to specify which mouse button you want to check. 0 is for the left button, 1 is for the right button, and 2 is for the middle button. The method will return a Boolean value indicating whether the specified mouse button has been pressed when using code like the example shown below.

bool isLeftButtonDown = Input.GetMouseButtonDown(0);
bool isRightButtonDown = Input.GetMouseButtonDown(1);
bool isMiddleButtonDown = Input.GetMouseButtonDown(2);

This code will display a message if the left mouse button is pressed:

if(Input.GetMouseButtonDown(0))
{
 print("The left mouse button was pressed");
}

Save the script and then run the scene. Check the output in the console when you click the left mouse button.

Mouse movement

Mouse movement is measured by reading the amount that the mouse has moved since the last frame, across the X and Y axes on screen.

The sample code below will read the mouse movement and display the value in the console. Place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float mouseXValue = Input.GetAxis("Mouse X");
float mouseYValue = Input.GetAxis("Mouse Y");
 
if(mouseXValue != 0)
{
 print("Mouse X movement: " + mouseXValue);
{
 
if(mouseYValue != 0)
{
 print("Mouse Y movement: " + mouseYValue);
{

Save the script and then run the scene. Check the output in the console when you move the mouse around the screen.

Transforming objects using scripts

This video tutorial will show you how to transform objects (move, rotate, scale) in your Unity game using C# scripts and also how to implement player interaction with the game by allowing players to transform objects using keypresses on their keyboard.

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

Here is some sample code with different object transformations assigned to different keypresses on the keyboard. You can change the transformations and assigned keys although it is a good idea to use the input manager rather than specific keypress detection so that your players have the option of remapping keys to suit their own preferences.

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 if (Input.GetKey (KeyCode.W)) {
 transform.Translate (0f,0f,0.1f);
 }
 if (Input.GetKey (KeyCode.S)) {
 transform.Translate (0f,0f,-0.1f);
 }
 
 if (Input.GetKey (KeyCode.D)) {
 transform.Translate (0.1f,0f,0f);
 }
 if (Input.GetKey (KeyCode.A)) {
 transform.Translate (-0.1f,0f,0f);
 }
 
 if (Input.GetKey (KeyCode.Z)) {
 transform.Rotate (0f,1f,0f);
 }
 
 if (Input.GetKey (KeyCode.X)) {
 transform.Rotate (0f,-1f,0f);
 }
 
 if (Input.GetKey (KeyCode.C)) {
 transform.localScale = new Vector3(1f,1f,1f);
 }
 
 if (Input.GetKey (KeyCode.V)) {
 transform.localScale = new Vector3(5f,5f,5f);
 }
 
 }
}

Note: If you find that the values for x, y and z axes seem to work the opposite to what you expect, it might be because you have the camera at a different angle. For example, if your camera is on the opposite side of your object, then pressing the key that is meant to move the object left might actually move it to the right.

Now try using variables to store the values for speed, eg:

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 public float turnSpeed = 5.0f;
 public float forwardSpeed = 0.25f;
 
 // Update is called once per frame
 void Update () {
 transform.Rotate(turnSpeed, 0.0f, 0.0f);
 transform.Translate(0.0f, 0.0f, forwardSpeed);
 }
}

Here is another method of moving objects on their own at a steady speed (this example does not include keyboard input).

using UnityEngine;
using System.Collections;
 
public class moveCube : MonoBehaviour {
 
 public float speed = 1.0f;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 transform.Translate (Vector3.forward * speed * Time.deltaTime);
 // This will move the cube forward on its own at steady speed
 // Vector3 is for 3D , Vector2 is for 2D
 // You can change Vector3.forward to Vector3.back, Vector3.left, or Vector3.right
 
 
 }
}