- Home /
How do I make an explosion affect my gameobjects?
I have some Cubes (with rigidbodies) in my scene that I want to blow up. How do I get them to react/get affected by for example a bomb thrown in front of them? I found the following code that works nice, but I would like the cubes to be thrown up in the air as well.
var explosionTime = 1.0; var explosionRadius = 3.0; var explosionPower = 500.0;
function executeCollision() { var colliders : Collider[] = Physics.OverlapSphere( transform.position, explosionRadius );
for( var hit in colliders )
{
if( hit.rigidbody )
hit.rigidbody.AddExplosionForce( explosionPower, transform.position, explosionRadius );
}
}
Answer by jjxtra · May 11, 2015 at 06:11 AM
Collider[] objects = UnityEngine.Physics.OverlapSphere(explosionCenterPosition, explosionRadius);
foreach (Collider h in objects)
{
Rigidbody r = h.GetComponent<Rigidbody>();
if (r != null)
{
r.AddExplosionForce(explosionForce, explosionCenterPosition, explosionRadius);
}
}
Answer by mrde · Jan 26, 2011 at 11:13 PM
add this code to your cub (with rigidbody) and it will give them velocity to up every mouse left click. not tested
void Update()
{
if (Input.GetButtonDown("Fire1")) {
rigidbody.velocity = transform.TransformDirection(new Vector3(0, 0, 5f));
}
Answer by Jessy · Jan 26, 2011 at 11:14 PM
This is the right answer. AddExplosionForce have a upward modifier that is 0.0f by default.
Answer by jtok4j · Apr 22, 2019 at 03:25 AM
My Two Cents:
For AddExplosionForce to work, the object you want to have flying around, must have:
a rigidbody AND (Mandatory)
a collider... simple, yet took me 30 minutes to figure out... Keep on Creating!
Answer by thomasfriday · Jul 12, 2021 at 06:05 PM
Here's a short Youtube video that covers exactly how to explode a cube: https://youtu.be/wcQqYOSteSs