Unity实现Flappy Bird游戏开发实战

2020-01-05 10:06:39刘景俊

Unity,游戏开发

游戏主场景

1 场景的来回切换 

通过2个场景,来回播放实现 
前一个场景完全移除屏幕后,立刻重新设置坐标,并且让柱子的位置随机出现


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

public class mapMove : MonoBehaviour {

  public float speed = 300f;
  public RectTransform tube1;
  public RectTransform tube2;

  private RectTransform transform;
  // Use this for initialization
  void Awake () {
    transform = GetComponent<RectTransform>(); 
  }

  // Update is called once per frame
  void Update () {

    // Translate:Moves the transform in the direction and distance of translation.

    // If you add or subtract to a value every frame chances are you should multiply with Time.deltaTime.
    // When you multiply with Time.deltaTime you essentially express: 
    // I want to move this object 10 meters per second instead of 10 meters per frame.
    transform.Translate (Vector3.left * Time.deltaTime * speed);

    // 如果前一个地图移到-764以外的地方,重放到764
    if (transform.anchoredPosition.x <= -764) {

      transform.anchoredPosition = new Vector2 (764, 0);
      // 设置水管的位置为随机出现,x不变,y随机出现
      tube1.anchoredPosition = new Vector2 (tube1.anchoredPosition.x, Random.Range (-110, 200));
      tube2.anchoredPosition = new Vector2 (tube2.anchoredPosition.x, Random.Range (-110, 200));
    }
  }
}

2 主要是鸟和柱子接触后产生的碰撞检测,首先需要设置鸟和柱子都为is Trigger触发器,因为这里不需要物理的碰撞效果

提前给所有柱子和上下面设置好tag,通过tag检测碰撞,停止移动地图并销毁鸟


// 碰撞检测
  void OnTriggerEnter2D (Collider2D other)
  {
    // 如果鸟碰到柱子
    if (other.gameObject.CompareTag("tube")) {

      if (!gameOver.activeSelf) {
        gameOver.SetActive (true);
        audioManager.singer.setAudio (audioClipType.hit);
      }

      // 通过地图的名字获取到地图移动