像素鸟无尽模式
任务3.1 相机跟随
步骤1. 创建CamCtrl.cs脚本
在Main Camera上添加新脚本CamCtrl.cs,并完成以下代码。
public class CamCtrl : MonoBehaviour {
public Transform target;
Vector3 offset;
// Use this for initialization
void Start () {
offset = transform.position-target.position;
}
// Update is called once per frame
void LateUpdate () {
transform.position = target.position + offset;
}
}
回到编辑器,对Target进行赋值,如图所示。
运行游戏,发现我们的相机已经可以跟着小鸟移动了。
步骤2. 限制相机高度
相机有时会穿帮,需要限制高度。修改脚本的LateUpdate方法如下。
void LateUpdate () {
Vector3 pos= target.position + offset;
if (pos.y > 0.9)
pos.y = 0.9f;
else if (pos.y < -0.9)
pos.y = -0.9f;
transform.position = pos;
}
任务3.2 无限地图
我们的思路是,将有限的图片进行重复使用,从而实现无限地图的效果。当最左侧的图片不可见时,将其移动到最右侧。
步骤1. 创建Endless.cs脚本
添加如下代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Endless : MonoBehaviour {
public float distance;
void OnBecameInvisible(){
transform.Translate(Vector3.right* distance * 3);
}
}
步骤2 实现无限地面
然后将脚本添加到back0、back1、back2,并在编辑器中设置distance为5.05。如图所示。
运行游戏进行测试,注意测试的时候需要关闭Scene视图。可以看到地面已经可以无限延长了,如图所示。
步骤3. 实现无限天空
同理,给bg0、bg1、bg2添加Endless脚本,并设置distance为3.02。
运行游戏测试,可以看到如图效果。
步骤4. 实现无限水管
同理,给pipeDown0、pipeDown1、pipeDown2添加Endless脚本,并设置distance为3。
运行游戏测试,可以看到水管也有无限个了。
任务3.3 水管随机高度
步骤1 创建RandomHeight.cs脚本
创建RandomHeight.cs脚本,添加如下代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomHeight : MonoBehaviour
{
void OnBecameVisible()
{
Vector3 pos = transform.position;
pos.y = Random.Range(-3f, -1.5f);
transform.position = pos;
}
}
步骤2 添加脚本
选中所有的pipeDown,全都添加RandomHeight脚本。
运行游戏,测试效果。可以看到管子已经可以产生随机高度了。