教程:爆炸桶

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

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. 工作原理

工作原理

4. 连锁反应

连锁反应

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

下一步:一波波的箱子。