http://download.csdn.net/detail/yy763496668/9838697 源碼下載地址
柱子的預製體製作的方法
拖拽一個精靈到情境中,Ctrl+D複製一份並將第二份z軸旋轉180°,對兩份同時添加Boxcollider 2D
並調整寬度。
建立一個空遊戲對象作為以上兩個遊對象的父物體,更名為Columns,添Rigidbody2D,BoxCollider2D組件。並進行相關的設定,如圖:
這裡的碰撞器一定勾選IsTrigger,這裡是用來檢測小鳥有沒有通過柱子,如果通過柱子,為以後加分準備。
像素鳥的柱子和背景一樣的速度移動,會比較舒服,所以我們同樣可以採用背景移動的指令碼
using System.Collections;using System.Collections.Generic;using UnityEngine;public class MoveObject : MonoBehaviour { private Rigidbody2D m_rigidbody; // Use this for initialization void Start () { //擷取自身的剛體 m_rigidbody = GetComponent<Rigidbody2D>(); //設定剛體的速度 m_rigidbody.velocity = new Vector2(-1.5f, 0); } // Update is called once per frame void Update () { }}
因為柱子在整個遊戲中是不斷出現的,為了避免產生柱子,銷毀柱子,我們採用對象池的方式,迴圈利用柱子
using System.Collections;using System.Collections.Generic;using UnityEngine;public class ColumnPools : MonoBehaviour { //預製體 public GameObject columPrefab; //對象池的數量 public int colmuPoolsize = 5; private GameObject[] columcnsPool; //讓預先產生的柱子步子啊攝像機範圍內,等我們需要的時候從這裡拿出一對放到出生的位置 private Vector2 objectPoolPosition = new Vector2(-17,-10); //當前柱子的索引 private int currentColumn = 0; private float timeSinceLastSpawned = 0.0f; //柱子出生的速度 public float SpawnRate; //出生點的X軸座標 private float spawnXPosition = 12f; //出生點的Y軸座標 private float spawnYPosition = -3f; // Use this for initialization void Start () { //執行個體化一個對象池 columcnsPool = new GameObject[colmuPoolsize]; //在對象池中預先執行個體化好多個柱子 for (int i = 0; i < columcnsPool.Length; i++) { columcnsPool[i] = Instantiate(columPrefab, objectPoolPosition, Quaternion.identity); } } // Update is called once per frame void Update () { ColumnPositionAndReuse(); } //柱子的位置設定和重複使用 private void ColumnPositionAndReuse() { timeSinceLastSpawned += Time.deltaTime; if (timeSinceLastSpawned > SpawnRate) { //保證柱子出現的時間在3s到4秒之間,避免柱子與柱子之間的距離相等 SpawnRate = Random.Range(3f,4f); //每次把柱子放在出生點的位置的時候都要把時間清零 timeSinceLastSpawned = 0.0f; //讓柱子的Y方向上有個起伏 spawnYPosition = Random.Range(-3.5f, 0); //設定出生點的位置吧 columcnsPool[currentColumn].transform.position = new Vector2(spawnXPosition, spawnYPosition); currentColumn++; if (currentColumn >= colmuPoolsize) { currentColumn = 0; } } }}