教程:爆炸桶
一个被射中或被猛烈撞击就会爆炸的桶。附近的一切都会被推开并受伤,摄像机也会震动。
1. 准备

做一个 Cylinder,给它刚体和 collider,把脚本放上去。
2. 脚本

Scripts/Explosive.cs
public class Explosive : Behaviour
{
public float radius = 6f;
public float push = 12f;
public float damage = 60f;
bool gone;
public void TakeDamage(object amount) { Explode(); }
public override void OnCollisionEnter(GameObject other)
{
// something fast ran into it
if (other.rigidbody.exists && other.rigidbody.velocity.Length > 8f) Explode();
}
void Explode()
{
if (gone) return;
gone = true;
foreach (GameObject near in Physics.OverlapSphere(transform.position, radius, gameObject))
{
// nearer things are pushed harder and hurt more
Vector3 away = near.transform.position - transform.position;
float strength = 1f - Mathf.Clamp01(away.Length / radius);
if (near.rigidbody.exists) near.rigidbody.AddImpulse((away.Normalized + Vector3.up * 0.5f) * push * strength);
near.SendMessage("TakeDamage", damage * strength);
}
Camera.Shake(0.6f, 0.5f);
Audio.PlayAt("Audio/explosion.wav", transform.position, 1f, 1f, 60f);
GameObject.Destroy(gameObject);
}
}
保存为 Scripts/Explosive.cs。
3. 工作原理

- 子弹调用
barrel.SendMessage("TakeDamage", 50f);桶的TakeDamage让它爆炸。这条消息见生命值。 - 高速碰撞也会让它爆炸:
OnCollisionEnter检查对方对象的速度。 Physics.OverlapSphere列出radius内的所有东西。对每一个,推力和伤害都随距离衰减:越近受影响越大。Camera.Shake让画面震动;Audio.PlayAt在桶的位置播放声音(添加Audio/explosion.wav)。
4. 连锁反应

把两个桶放近些:第一个的爆炸对第二个调用 TakeDamage,第二个也爆炸。
下一步:一波波的箱子。