Flipping a sprite horizontally

Perhaps the simplest 2D animation is a simple flip, from facing left to facing right, or facing up to facing down, and so on. In this recipe we'll add a cute bug sprite to the scene, and write a short script to flip its horizontal direction when the Left and Right arrow keys are pressed.

Flipping a sprite horizontally

Getting ready

For this recipe, we have prepared the image you need in a folder named Sprites in folder 1362_03_01.

How to do it...

To flip an object horizontally with arrow key presses, follow these steps:

  1. Create a new Unity 2D project.
  2. Import the provided image EnemyBug.png.
  3. Drag an instance of the red Enemy Bug image from the Project | Sprites folder into the scene. Position this GameObject at (0, 0, 0) and scale to (2, 2, 2).
  4. Add an instance of C# script class BugFlip as a component to your Enemy Bug GameObject:
    using UnityEngine;
    using System.Collections;
    
    public class BugFlip : MonoBehaviour {
      private bool facingRight = true;
    
      void Update() {
        if (Input.GetKeyDown(KeyCode.LeftArrow) && facingRight)
          Flip ();
        if (Input.GetKeyDown(KeyCode.RightArrow) && !facingRight)
          Flip();
      }
    
      void Flip (){
        // Switch the way the player is labelled as facing.
        facingRight = !facingRight;
    
        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
      }
    }
  5. When you run your scene, pressing the Left and Right arrow keys should make the bug face left or right correspondingly.

How it works...

The C# class defines a Boolean variable facingRight, which stores a true/false value corresponding to whether or not the bug is facing right or not. Since our bug sprite is initially facing right, then we set the initial value of facingRight to true to match this.

Method Update(), every frame, checks to see if the Left or Right arrow keys have been pressed. If the Left arrow key is pressed and the bug is facing right, then method Flip() is called, likewise if the Right arrow key is pressed and the bug is facing left (that is, facing right is false), again method Flip() is called.

Method Flip() performs two actions, the first simply reverses the true/false value in variable facingRight. The second action changes the +/- sign of the X-value of the localScale property of the transform. Reversing the sign of the localScale results in the 2D flip that we desire. Look inside the PlayerControl script for the BeanMan character in the next recipe – you'll see exactly the same Flip() method being used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.245.1