Make random the explosions of the crates

In the video “Destructible Crate Parts”, is not added the same random way of exploding the crates, same as we do with the ragdolls when they fall.

If you are interested, you just need to add 1 line and modify another one from the “Damage()” method. Here is the full method, with comments:

public void Damage()
    {
        // Instantiate the crateDestroyedPrefab in the same position and rotation of the original crate
        Transform crateDestroyedTransform = Instantiate(crateDestroyedPrefab, transform.position, transform.rotation);

        // Apply the explosion force on the CrateDestroyed children parts.
        Vector3 randomDir = new Vector3(UnityEngine.Random.Range(-1, +1), 0, UnityEngine.Random.Range(-1, +1));// To add some randomDir in the cratePartes children when they will explode.
        ApplyExplosionToChildren(crateDestroyedTransform, 150f, transform.position + randomDir, 10f);

        // Destroy the original crate.
        Destroy(gameObject);

        OnAnyDestroyed?.Invoke(this, EventArgs.Empty);
    }

I hope you might find it useful!

5 Likes

Thank you @mogutaru

Note that this is going to give you a value between -1 and 0 because the integer version of Random.Range returns a value between min inclusive and max exclusive. To get a value between -1 and 1 (which I’m sure you’d want in this case) you should use the float version: UnityEngine.Random.Range(-1f, +1f) or UnityEngine.value * 2f - 1f

2 Likes

Yup good tip, just adding a tiny bit of randomness is the perfect solution, good job!

Privacy & Terms