天天看点

FlappyBird开发总结(五)——背景延伸

FlappyBird开发总结(五)——背景延伸

在写脚本之前,我先上个图把背景中的物体结构表达清楚一下

我觉得图片应该表达清楚了,要提示一点,这个GameObject物体的位置要自己把握好,不然游戏效果有点差。

好了,这次要写的脚本是放在这个GameObject物体下的,记住GameObject是空物体,然后给他一个碰撞器勾选IsTriger成为触发器(不知道说法对不对。。。),然后我们把背景1的预制物体的改动apply一下,让该背景1这个物体的改动应用到背景2,背景3,背景4上。

MoveTarget.cs

using UnityEngine;
using System.Collections;

public class MoveTarget : MonoBehaviour {

    public Transform currentBackGround;
    public Pipe pipe1;//Pipe.cs脚本的引用,下面再提
    public Pipe pipe2;

    // Use this for initialization
    void Start () {

    }

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

    }

    void OnTriggerEnter(Collider gameObject)
    {
        if (gameObject.tag == "Player")
        {
            Transform firstBackGround = GameManager.gameInstance.firstBackGround;

            currentBackGround.position = new Vector3(firstBackGround.position.x + , currentBackGround.position.y, currentBackGround.position.z);

            GameManager.gameInstance.firstBackGround = currentBackGround;

            pipe1.RundomPosition();
            pipe2.RundomPosition();

        }

    }
}
           

好了,这样就能在小鸟接触到背景1的GameObject物体后让背景1移动到背景4后面,然后当接触到背景2的GameObject物体后让背景2又移动到移动后的背景1的后面,如此循环,代码很清楚,不多做解释。

然而这里多了调用了一个方法

这是干什么的呢?

首先我们想象,一开始的4个背景的上下管道的位置是固定一样的吧,游戏当然不能这样,我们得让上下管道的位置在游戏进行时改变才能增加游戏的那个什么趣味性吧?(请允许我用这个词。。。想不到词了)

首先,我们得吧PipeUp和PipeDown放到共同的一个空物体下,也就是说成为该空物体的子物体,这个空物体就是上图中的Pipe1和Pipe2了,so,现在我们该解决问题了,给Pipe1和Pipe2(所有背景都要这样操作哦,也就是上面红色物体的apply一下),当然你最好都看一下确定一下是不是都一样。现在呢,我们写一个脚本Pipe.cs,注意是给到每个上下管道上的父物体!

using UnityEngine;
using System.Collections;

public class Pipe : MonoBehaviour {

    private float minPositionY = -f;//此处的最小值和下面的最大值自己去算啦 ,不解释
    private float maxPositionY = f;
    public GameObject scores;//NGUI做的UI,暂时用不到,计分用

    public void RundomPosition()
    {
        float positionY = Random.Range(minPositionY, maxPositionY);//随机数
        this.transform.localPosition = new Vector3(this.transform.localPosition.x, positionY, this.transform.localPosition.z);
//注意因为Pipe1和Pipe2是背景的子物体,所以这里是用localPosition!
//下面的可以先不了解,作用是每当小鸟飞过管道了,就加上一分,audio.Play()就是播放加分的音源了
    void OnTriggerExit(Collider gameObject)
    {


        if(gameObject.tag=="Player")
        {
            audio.Play();
            GameManager.gameInstance.currentScores++;
          //  Debug.Log(GameManager.gameInstance.currentScores);
            scores.GetComponent<UILabel>().text = GameManager.gameInstance.currentScores + "";
        }

    }


}
           

写完这两个脚本后,背景的无限延伸就实现了。

继续阅读