二、障碍物
障碍物只要定时产生,随机设定偏移量,然后添加向左运动的速度就行了,同时要设定自动销毁的时间,回收障碍物,否则内存占用会越来越大。
这里用了三个脚本,分别是上下障碍物和障碍物生成脚本。附加到一个空物体上就行了。
GenerateObstacle.cs
using UnityEngine;
using System.Collections;
public class GenrateObstacle : MonoBehaviour {
public GameObject obstacle;
public GameObject obstacle1;
public float startTime = 1f;
public float gapTime=1.5f;
public float gapDistance = 13;
private Vector3 gapVector;
private Vector3 midVector;
// Use this for initialization
void Start () {
InvokeRepeating("InitiateObstacle", startTime, gapTime);
gapVector = new Vector3(0, gapDistance / 2, 0);
}
void InitiateObstacle()
{
midVector = new Vector3(8,Random.Range(-3.2f, 3.2f),0);
Instantiate(obstacle, midVector+gapVector,new Quaternion(0,0,180,0));
Instantiate(obstacle1, midVector-gapVector, Quaternion.identity);
}
}
Obstacle.cs
using UnityEngine;
using System.Collections;
public class Obstacle : MonoBehaviour {
public float speed = -8f;
private Rigidbody body;
private Transform player;
private bool isPassed = false;
// Use this for initialization
void Start () {
Destroy(this.gameObject, 4);
body = this.GetComponent<Rigidbody>();
body.velocity = new Vector3(speed, 0, 0);
player = GameObject.FindGameObjectWithTag("Bird").transform;
}
// Update is called once per frame
void Update () {
if (player.transform.position.x > transform.position.x && isPassed == false)
{
isPassed = true;
Score.instance.GetScore();
}
}
}
Obstacle1.cs
using UnityEngine;
using System.Collections;
public class Obstacle1 : MonoBehaviour {
public float speed = -8f;
private Rigidbody body;
private Transform player;
private bool isPassed = false;
// Use this for initialization
void Start()
{
Destroy(this.gameObject, 4);
body = this.GetComponent<Rigidbody>();
body.velocity = new Vector3(speed, 0, 0);
player = GameObject.FindGameObjectWithTag("Bird").transform;
}
}










