Unity实现Flappy Bird游戏开发实战

2020-01-05 10:06:39刘景俊
脚本 mapMove map1 = GameObject.Find ("map1").GetComponent<mapMove> (); map1.enabled = false; mapMove map2 = GameObject.Find ("map2").GetComponent<mapMove> (); map2.enabled = false; Rigidbody2D playerRigidBody2D = GameObject.Find ("player").GetComponent<Rigidbody2D> (); Destroy (playerRigidBody2D); } }

3 音效设置和鸟的朝向问题

因为鸟震动翅膀的声音需要和其他音效不是一个线程,所以只能单独领出来写


// playerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerController : MonoBehaviour {

  private Rigidbody2D player;

  public AudioSource playerAudio;
  public float speed;
  // Use this for initialization
  void Start () {
    player = GetComponent<Rigidbody2D>();
    // 重置分数
    gameSingleton.getSingleton ().score = 0;
  }

  // Update is called once per frame
  void Update () {
    // 如果鸟被销毁游戏结束了,直接返回
    if (player == null) { return; }

    // 当点击鼠标,给鸟一个向上的速度
    if (Input.GetMouseButtonDown (0)) {
      player.velocity = new Vector2(0, speed);
//     audioManager.singer.setAudio (audioClipType.wing);
      // 因为翅膀的声音和过柱子的声音,不能是同个线程的
      if (!gameSingleton.getSingleton ().isMute) {
        playerAudio.Play();
      }

    }

    // 通过判断鸟的速度正负设计鸟的头的转向,
    if (player.velocity.y > 0) {
      transform.eulerAngles = new Vector3 (0, 0, 45);
    } else {
      transform.eulerAngles = new Vector3 (0, 0, -45);
    }
  }

}

4 分数的计算

这里需要再次用到触碰检测,给柱子之间空隙加个透明的检测器,每次一过柱子就加一分

用单例类存储分数等数据:


// gameSingleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gameSingleton {

  // 使用单例模式记录分数
  // 显然单例模式的要点有三个;一是某个类只能有一个实例;
  // 二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。
  // 从具体实现角度来说,就是以下三点:一是单例模式的类只提供私有的构造函数,
  // 二是类定义中含有一个该类的静态私有对象,三是该类提供了一个静态的公有的函数用于创建或获取它本身的静态私有对象。

  public float score;
  public float bestScore;
  public bool isMute; // 用来控制音效
// public bool isFirstToPlay;

  // 含有一个静态私有对象,这也是唯一一个对象
  private static gameSingleton singer;

  // 私有的构造函数
  private gameSingleton () {
    score = 0;
    bestScore = 0;
    isMute = false;
//   isFirstToPlay = true;
  }

  // 提供一个静态的公有函数 用于创建或获取本身的静态私有对象
  public static gameSingleton getSingleton() {
    if (singer == null) {
      singer = new gameSingleton ();
    }
    return singer;
  }

  public void setBestScore() {
    if (score > bestScore) {
      bestScore = score;
    }
  }

}