# 【Unity3D】游戏常用点整理-飞机射击类游戏

1）飞机控制

在有限的范围内上下左右移动

public  class Boundary {
public float xMin = -6.5f;
public float xMax = 6.5f;
public float zMin = -1.5f;
public float zMax = 11.0f;
}

public Boundary boundary;

void FixedUpdate() {
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 move = new Vector3(h, 0f, v);

rigidbody.velocity = speed * move;
rigidbody.position = new Vector3(
Mathf.Clamp(rigidbody.position.x,boundary.xMin, boundary.xMax),
0,
Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax)
);
}

2）发射子弹

    public GameObject bolt;//子弹
public Transform spawnpos;//  发射位置

public float fireRate = 0.25f;//发射时间间隔
private float nextFire;//下次发射时间

public AudioClip fire;

void Update() {
if (Input.GetButton("Fire1")&&(Time.time>nextFire)) {
nextFire = Time.time + fireRate;
Instantiate(bolt, spawnpos.position, spawnpos.rotation);
audio.PlayOneShot(fire);
}
}

3）生成敌人

public Vector3 spawnValues;

void Enemy() {
GameObject o = enemy[Random.Range(0, enemy.Length)];
Vector3 p = new Vector3(Random.Range(-spawnValues.x,spawnValues.x),spawnValues.y,spawnValues.z);
Quaternion q = Quaternion.identity;
Instantiate(o, p, q);
}

enemy数组装不同的敌人

4）敌人移动

public float speed = 10;
void Start () {
rigidbody.velocity = transform.forward * speed;
}

5）几波敌人的进攻

    public int NumPerWave = 10;//一波敌人数量
public float spawnWait = 1f;//敌人间隔出现时间
public float startWait = 2f;//游戏开始等待时间
public float waveWait = 4f;//每两波间隔出现时间
void Start () {
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves() {
yield return new WaitForSeconds(startWait);
while (true) {
for (int i = 0; i < NumPerWave; i++) {
Enemy();//生成敌人
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}

}

6）kill与反kill

public GameObject enemyExplosion;
public GameObject playerExplosion;

void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "player")
{
Instantiate(playerExplosion, this.transform.position, this.transform.rotation);
}
Destroy(other.gameObject);
Destroy(this.gameObject);
Instantiate(enemyExplosion, this.transform.position, this.transform.rotation);
}

7）移动

 public float speed = 10;
void Start () {
rigidbody.velocity = transform.forward * speed;
}
8）边界设置（出边界，就销毁）

public class DestroyByBoundary : MonoBehaviour {

void OnTriggerExit(Collider other) {
Destroy(other.gameObject);
}
}
9）让敌人滚动起来

public class RandomRotater : MonoBehaviour {
public float tumble = 5;
void Start () {
rigidbody.angularVelocity = Random.insideUnitSphere * tumble;
}
}

10) bang 几秒后，自动销毁对象

public class DestroyByTime : MonoBehaviour {
}