Bird.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. namespace Shapes2D {
  2. using UnityEngine;
  3. using System.Collections;
  4. using UnityEngine.EventSystems;
  5. [RequireComponent(typeof(Rigidbody2D))]
  6. [RequireComponent(typeof(Animator))]
  7. public class Bird : MonoBehaviour {
  8. Rigidbody2D rb;
  9. public float force = 8;
  10. bool dead, playing;
  11. Vector3 startPosition;
  12. int score = 0;
  13. // Use this for initialization
  14. void Start () {
  15. rb = GetComponent<Rigidbody2D>();
  16. startPosition = transform.position;
  17. Reset();
  18. }
  19. void OnTriggerEnter2D(Collider2D other) {
  20. if (other.name == "Pass Trigger") {
  21. score ++;
  22. return;
  23. }
  24. Die();
  25. }
  26. public int GetScore() {
  27. return score;
  28. }
  29. void OnCollisionEnter2D(Collision2D coll) {
  30. Die();
  31. }
  32. public bool IsDead() {
  33. return dead;
  34. }
  35. public void Reset() {
  36. transform.position = startPosition;
  37. GetComponent<Animator>().enabled = false;
  38. rb.isKinematic = true;
  39. dead = false;
  40. playing = false;
  41. transform.rotation = Quaternion.Euler(0, 0, 0);
  42. score = 0;
  43. }
  44. public bool IsPlaying() {
  45. return playing;
  46. }
  47. public void Play() {
  48. if (dead)
  49. Reset();
  50. GetComponent<Animator>().enabled = true;
  51. rb.isKinematic = false;
  52. playing = true;
  53. Flap();
  54. }
  55. void Die() {
  56. GetComponent<Animator>().enabled = false;
  57. rb.velocity = new Vector2(0, 0);
  58. rb.AddForce(new Vector2(0, -force * 2), ForceMode2D.Impulse);
  59. dead = true;
  60. playing = false;
  61. transform.rotation = Quaternion.Euler(0, 0, -50);
  62. }
  63. void Flap() {
  64. if (rb.velocity.y < 0)
  65. rb.velocity = new Vector2(rb.velocity.x, 0);
  66. rb.AddForce(new Vector2(0, force), ForceMode2D.Impulse);
  67. transform.rotation = Quaternion.Euler(0, 0, 30);
  68. }
  69. void Update() {
  70. if (!playing)
  71. return;
  72. if (InputUtils.MouseDownOrTap()
  73. && !EventSystem.current.IsPointerOverGameObject())
  74. Flap();
  75. float theta = Mathf.LerpAngle(-30, 50,
  76. Mathf.Clamp(rb.velocity.y, -1, 1));
  77. transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, theta), Time.deltaTime * 5);
  78. }
  79. }
  80. }