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.
For this recipe, we have prepared the image you need in a folder named Sprites
in folder 1362_03_01
.
To flip an object horizontally with arrow key presses, follow these steps:
EnemyBug.png
.0
, 0
, 0
) and scale to (2
, 2
, 2
).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; } }
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.
52.15.245.1