Bird.cs
2.06 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D),typeof(Animator))]
public class Bird : MonoBehaviour
{
public float upForce; //Upward force of the "flap".
private bool isDead = false; //Has the player collided with a wall?
private Animator anim; //Reference to the Animator component.
private Rigidbody2D rb2d; //Holds a reference to the Rigidbody2D component of the bird.
public IUnityInputService UnityInput;
public bool IsDead
{
get { return isDead; }
private set { isDead = value; }
}
void Start()
{
//Get reference to the Animator component attached to this GameObject.
anim = GetComponent<Animator> ();
//Get and store a reference to the Rigidbody2D attached to this GameObject.
rb2d = GetComponent<Rigidbody2D>();
if (UnityInput == null)
{
UnityInput = new UnityInputService();
}
}
void Update()
{
//Don't allow control if the bird has died.
if (isDead == false)
{
//Look for input to trigger a "flap".
if (UnityInput.GetButtonDown("Fire1"))
{
Jump();
}
}
}
void OnCollisionEnter2D(Collision2D other)
{
// Zero out the bird's velocity
rb2d.velocity = Vector2.zero;
// If the bird collides with something set it to dead...
isDead = true;
//...tell the Animator about it...
anim.SetTrigger("Die");
//...and tell the game control about it.
if (GameControl.instance != null)
{
GameControl.instance.BirdDied();
}
}
void OnTriggerEnter2D(Collider2D other)
{
//If the bird hits the trigger collider in between the columns then
//tell the game control that the bird scored.
GameControl.instance.BirdScored();
}
public void Jump()
{
//...tell the animator about it and then...
anim.SetTrigger("Flap");
//...zero out the birds current y velocity before...
rb2d.velocity = Vector2.zero;
// new Vector2(rb2d.velocity.x, 0);
//..giving the bird some upward force.
rb2d.AddForce(new Vector2(0, upForce));
}
}