Tutorial: an exploding barrel

A barrel that blows up when it is shot or hit hard. Everything nearby is pushed away and hurt and the camera shakes.

1. Set up

Set up

Make a Cylinder, give it a rigid body and a collider, and put the script on it.

2. The script

The script

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);
    }
}

Save it as Scripts/Explosive.cs.

3. How it works

How it works

4. Chain reactions

Chain reactions

Put two barrels close together: the first one's blast calls TakeDamage on the second, which explodes too.

Next: waves of crates.