Lesson 5: Animation

Piskelapp

The web application, Piskelapp.com, is a great tool for designing pixel art. Visit the site, create a new “Sprite,” and reproduce the two images below in separate frames.

Once you finish reproducing the images above, increase the size 4 times (x4) as in the image, and save it as a PNG. We will import these sprites into our Sprite folder.

Level_02

If you’ve already created a level that you’d like to preserve, simply duplicate the “Level_01” scene and call it “Level_02.” Duplicate the “Bird Prefab” as well and place the new prefab in the new level under the “MainScene” script.

Bird Script

To “wire up” the animation, you’ll have to modify your “BirdScript.” The complete script is available below. Make the requisite changes to yours based on what you see below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

using UnityEngine;

using System.Collections;

using UnityEngine.SceneManagement;

publicclassBirdScript:MonoBehaviour{

// this global variable will be set from the inspector. Represents bird jump force

publicVector2 jumpForce=newVector2();

//This is where you'll set the sprites in the editor

publicSprite fly;

publicSprite flap;

privateSpriteRenderer spriteRenderer;

// function to be executed once the bird is created

voidStart(){

// placing the bird

transform.position=newVector2(-2f,0f);

//tk

spriteRenderer=GetComponent<SpriteRenderer>();

if(spriteRenderer.sprite==null){

spriteRenderer.sprite=fly;

}

}

// function to be executed at each frame

voidUpdate(){

// waiting for mouse input

if(Input.GetButtonDown("Fire1")){

// setting bird's rigid body velocity to zero

GetComponent<Rigidbody2D>().velocity=Vector2.zero;

// adding jump force to bird's rigid body

GetComponent<Rigidbody2D>().AddForce(jumpForce);

AudioSource audio=GetComponent<AudioSource>();

audio.Play();

//this triggers the animation every time you left click

spriteRenderer.sprite=flap;

}

//this switches the sprite back when you release the left click

if(Input.GetButtonUp("Fire1")){

spriteRenderer.sprite=fly;

}

// getting the real position, in pixels, of the bird on the stage

Vector2 stagePos=Camera.main.WorldToScreenPoint(transform.position);

// if the bird leaves the stage...

if(stagePos.y>Screen.height||stagePos.y<0){

// ... call die function

die();

}

}

// function to be executed once the bird enters in collision with anything