8 子彈碰撞處理
為了處理子彈打到坦克的傷害我們在這里新建一個Shell.cs
子彈有兩種情況,碰到坦克炸開,沒有碰到坦克則過2s子彈銷毀.
void Start () {
Destroy (gameObject, 2); // 過2秒子彈銷毀 }
碰到子彈我們這里使用OnTriggerEnter,要想這個發生首先要確保Shell預設體里面Collider的Is Trigger已經被選中了.

然后在OnTriggerEnter里面我們檢測在一定范圍之內的坦克有哪些.
private float radius = 5f; // 爆炸范圍
public LayerMask mask;
我們需要指定Tank屬於哪個LayerMask

將Shell.cs掛載到Shell預設體上,設置相同的LayerMask

然后我們使用Physics.OverlapSphere就可以找到以子彈為中心,radius范圍之內的所有坦克
Collider[] colliders = Physics.OverlapSphere( transform.position, radius, mask);
然后遍歷所有坦克,根據兩者之間的距離和最大傷害值100計算坦克所受傷害
Health health = colliders [i].GetComponent<Health> (); // 找到Health組件
float damage = Vector3.Distance (transform.position, colliders [i].transform.position) / 5 * 100; // 根據實際距離按比例計算傷害值 if (health) health.TakeDamage (damage); // 坦克承受傷害
另外一個就是為坦克添加被炸開的效果
Rigidbody rb = colliders [i].GetComponent<Rigidbody> (); // 剛體組件
if( rb ) rb.AddExplosionForce (1000f, transform.position, radius); // 坦克被炸開
最后是子彈炸毀效果和音效
private ParticleSystem ps; // 爆炸效果
private AudioSource audioSource; // 聲源
在Start里面獲取ps和audioSource
ps = GetComponentInChildren <ParticleSystem> ();
audioSource = GetComponent<AudioSource> ();
然后在OnTriggerEnter最后播放爆炸效果,爆炸運行,銷毀gameObject
ps.transform.parent = null; // 將爆炸效果從Shell里面移出
ps.Play (); // 播放爆炸效果 audioSource.Play (); // 播放爆炸音效 Destroy (ps.gameObject, ps.duration); // 爆炸效果播放完畢之后移出爆炸效果的gameObject Destroy (gameObject); // 移出Shell的gameObject
最終版本代碼為:Shell.cs

using UnityEngine;
using System.Collections;
public class Shell : MonoBehaviour {
private float radius = 5f; // 爆炸范圍
public LayerMask mask; // tank
private ParticleSystem ps; // 爆炸效果
private AudioSource audioSource; // 聲源 // Use this for initialization void Start () { Destroy (gameObject, 2); // 過2秒子彈銷毀 ps = GetComponentInChildren <ParticleSystem> (); // 獲取子對象的ParticleSystem audioSource = GetComponent<AudioSource> (); // 獲取音源 } // Update is called once per frame void OnTriggerEnter ( Collider other) { Collider[] colliders = Physics.OverlapSphere( transform.position, radius, mask); // radius范圍內所有坦克 for (int i = 0; i < colliders.Length; i++) { // 遍歷所有坦克 Health health = colliders [i].GetComponent<Health> (); // 找到Health組件 float damage = Vector3.Distance (transform.position, colliders [i].transform.position) / 5 * 100; // 根據實際距離按比例計算傷害值 if (health) health.TakeDamage (damage); // 坦克承受傷害 Rigidbody rb = colliders [i].GetComponent<Rigidbody> (); // 剛體組件 if( rb ) rb.AddExplosionForce (1000f, transform.position, radius); // 坦克被炸開 } ps.transform.parent = null; // 將爆炸效果從Shell里面移出 ps.Play (); // 播放爆炸效果 audioSource.Play (); // 播放爆炸音效 Destroy (ps.gameObject, ps.duration); // 爆炸效果播放完畢之后移出爆炸效果的gameObject Destroy (gameObject); // 移出Shell的gameObject }
}
---------------------------我是目錄分割線---------------------------
《杜增強講Unity之Tanks坦克大戰》4-坦克的移動和旋轉
《杜增強講Unity之Tanks坦克大戰》9-發射子彈時蓄力
《杜增強講Unity之Tanks坦克大戰》11-游戲流程控制
---------------------------我是目錄分割線---------------------------