Tag Archives: sprite

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

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