- Home /
How to shatter 2d objects without rigidbody?
Hi! I want to shatter a 2d object, I am looking for options and most of them using shattered prefabs with rigidbodys. But I can't use rigidbody because my game is top-down so there is no collider under the object and i can't use gravity. Is there other options to shatter a 2d object without using rigidbody?
Rigidbody2D, like RigidBody, has gravity parameters. If your game is 2D from top-down, then in the Rigidbody2D parameters there is gravityScale, which can be set to zero if gravity is not needed.
But when you instantiate shattered prefab , shattered the parts needs force and gravity to fall. Am i wrong?
I mean most of the people i saw do it like this; For example there is a box and box's pieces like it shattered. They put together the parts and add rigidbody components to them then save it as prefab. When something hit the box they destroy the un-shattered box and instantiate shattered prefab on originals place. And with rigidbody, pieces starts falling like its shattered. This technic can work when the game is side-scrolled but in my case its top-down so I can't use gravity, I need something else.
Answer by DenisIsDenis · Jun 10, 2021 at 12:26 PM
Here is an example script that splits an object into pieces when hitting an object tagged "Bullet":
using UnityEngine;
public class ShatterGameObject : MonoBehaviour
{
public GameObject shatteredGameObject;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Bullet"))
return;
var shatteredObj = Instantiate(shatteredGameObject, transform.position, transform.rotation);
var rigidbodies = shatteredObj.GetComponentsInChildren<Rigidbody2D>();
foreach (Rigidbody2D rb2d in rigidbodies)
{
Vector2 force = rb2d.transform.position - collision.transform.position;
rb2d.AddForce(force.normalized * 100);
}
Destroy(gameObject);
}
}
Making a simple scene I got the following result (GIF):
Main Object and Shards parameters (GIF): (Note: I have increased the LinearDrag value to slow down the shards over time).
Thank you so much, it worked very well! Especially the pieces seem to be scattered all over the floor and this looks realistic. Thank you very much for taking the time to solve this problem :))