預製體制作
導入要用到的模型,添加CapsuleCollider組件和Rigidbody組件,並設置好相關屬性。
添加這兩個組件是爲了實現爆炸的效果。
實現原理
用一個變量來記錄油桶受到攻擊的次數,當受到三次以上的攻擊時就觸發爆炸。
爆炸時,以當前油桶爲中心獲取爆炸範圍內的物體。並使用Rigidbody組件給它們添加一個爆炸的力並播放爆炸的粒子特效。
public class BarrelCtrl : MonoBehaviour {
public GameObject expEffect;//爆炸的特效
public float expRadius = 10.0f;//爆炸半徑
private int hitCount = 0;//受到攻擊次數
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.tag == "BULLET")
{
Destroy(collision.gameObject);
if(++hitCount >= 3)
{
ExpBarrel();
}
}
}
private void ExpBarrel()
{
Instantiate(expEffect, this.transform.position, Quaternion.identity);
//獲取爆炸範圍內的物體
Collider[] colls = Physics.OverlapSphere(this.transform.position, expRadius);
foreach(Collider coll in colls)
{
Rigidbody rig = coll.GetComponent<Rigidbody>();
if(rig != null)
{
rig.mass = 1.0f;//重置質量
//施加爆炸的力
rig.AddExplosionForce(1000.0f, this.transform.position, 10.0f, 300.0f);
}
}
Destroy(this.gameObject, 2.0f);
}
}