Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Exploding cube

Discussion in 'Scripting' started by Hello_Lp, Mar 6, 2014.

  1. Hello_Lp

    Hello_Lp

    Joined:
    Mar 23, 2013
    Posts:
    10
    If I have a container that contain 125 smaller cubes with rigid bodies. How do I make the cubes explode in the direction that I want?

    I tried something like this:

    Code (csharp):
    1. public class ExplodingCube : MonoBehaviour
    2. {
    3.         public float radius;
    4.         public float power;
    5.  
    6.         void Start ()
    7.         {
    8.                 foreach (Transform child in transform) {
    9.                         child.rigidbody.AddExplosionForce (power, transform.position, radius);
    10.                 }
    11.         }
    12. }
    What I want is for a ball to roll towards the container. When it collides, the cubes insider the container will exploded outwards away form the ball.
     
  2. AlwaysSunny

    AlwaysSunny

    Joined:
    Sep 15, 2011
    Posts:
    260
    Specifically, how doesn't this work? You should destroy or disable any collider on the container when you call for your explosion, or that could cause problems. Depending on your needs, it seems like your child rigidbodies should be kinematic before the explosion, but set to non-kinematic during and afterward. Also, it's usually (always?) a good idea to avoid having rigidbodies who are children of a dynamic object. This can cause all sorts of trouble - the physics system expects to work with unparented objects or objects whose parents are static.
     
  3. Hello_Lp

    Hello_Lp

    Joined:
    Mar 23, 2013
    Posts:
    10
    Found the problem. The position is the world position of the explosion I believe. You need to add explosion to each rigid body that you want affected by the explosion.

    Code (csharp):
    1.         public void Explode (Vector3 position)
    2.         {
    3.                 foreach (Transform child in transform) {
    4.                         foreach (Transform grandchild in child) {
    5.                                 foreach (Transform greatgrandchild in grandchild) {
    6.                                         greatgrandchild.rigidbody.AddExplosionForce (power, position, radius);
    7.                                 }
    8.                         }
    9.                 }
    10.         }