How to do it...

To create a destructible object, follow these steps:

  1. Import the normal and shattered objects to Unity. In our example, we have an object called Ball and the other one is called BallFractured.
  2. Drag and drop both objects into the scene.
  3. Select all child game objects (pieces) of the BallFractured game object. Add the Rigidbody and Mesh Collider components to them. Set the Mesh Collider to Convex.
  4. Create a prefab from the BallFractured game object (containing all the pieces).
  5. Select the Ball game object and add a Rigidbody and a Sphere Collider to it (or another type, depending on the shape of your object).
  6. Write a new C# script and call it SpawnFracturedObject.cs. In this script, we have a void Fracture() function that spawns a fractured game object prefab (our BallFractured), applies velocity to all its pieces, and destroys the main object (Ball):
      void Fracture() 
      { 
          GetComponent<Collider>().enabled = false; 
          GameObject fracturedObject = 
          (GameObject)GameObject.Instantiate(fracturedObject 
          Prefab, transform.position, transform.rotation); 
     
          Rigidbody[] rigidBodies = 
          fracturedObject.GetComponentsInChildren<Rigidbody>    (); 
     
          for (int i = 0; i < rigidBodies.Length; i++) 
          { 
              rigidBodies[i].velocity += 
              lastRigidBodyVelocity; 
          } 
          Destroy(gameObject); 
      } 
  1. The void Fracture() function is called when our main object collides with anything:
      void OnCollisionEnter(Collision col) 
      { 
          Fracture(); 
      } 
  1. The Ball's velocity is saved every frame to the float lastRigidBodyVelocity variable (in the FixedUpdate() function):
      void FixedUpdate () { 
          lastRigidBodyVelocity = rb.velocity; 
      } 
  1. Assign the script to the Ball game object and drag the BallFractured prefab onto the Fractured Object Prefab field in the Inspector.
  2. Play the game to see the effect:
Before and after collision
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151