Tutoriel : un baril explosif

Un baril qui explose quand on lui tire dessus ou qu'on le frappe fort. Tout ce qui est proche est repoussé et blessé, et la caméra tremble.

1. Préparation

Préparation

Faites un Cylinder, donnez-lui un corps rigide et un collider, et mettez le script dessus.

2. Le script

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

Enregistrez-le sous Scripts/Explosive.cs.

3. Comment ça marche

Comment ça marche

4. Réactions en chaîne

Réactions en chaîne

Mettez deux barils proches : le souffle du premier appelle TakeDamage sur le second, qui explose aussi.

Suite : des vagues de caisses.