- Home /
Add Explosion Force to children?
I am making a game similar to Space Invaders, but all of the aliens are made of cubes. I'm trying to make it so that when I shoot an alien, it will explode from all the cubes it is made of, but I can't seem to get it to work.
Here's the code I have:
public class EnemyExplode : MonoBehaviour {
public float explosionRadius = 5.0f;
public float explosionPower = 10.0f;
void OnTriggerEnter() {
foreach (Transform child in transform) {
child.rigidbody.useGravity = true;
child.rigidbody.AddExplosionForce(explosionPower,transform.position,explosionRadius,3.0f);
}
collider.enabled = false;
}
}
When I shoot an enemy the children just fall.
Answer by aldonaletto · Nov 19, 2012 at 12:01 AM
The script below worked fine: I set Is Kinematic and Use Gravity in all cubes (kinematic rigidbodies ignore useGravity), and made sure the explosion would only occur when a projectile tagged "Bullet" entered the trigger (the cubes themselves generate OnTriggerEnter when they are created). Also the explosionPower should be increased, but remember that the Inspector has the memory of an elephant, and will keep the old value even if the script is changed - modify explosionPower directly in the Inspector. Notice also that when the explosion occurs, I set isKinematic to false before applying the explosion force - the gravity enters automatically because Use Gravity was already set:
public class EnemyExplode : MonoBehaviour {
public float explosionRadius = 8.0f;
public float explosionPower = 100.0f;
void OnTriggerEnter(Collider other) {
if (other.tag == "Bullet"){
foreach (Transform child in transform) {
child.rigidbody.isKinematic = false;
child.rigidbody.AddExplosionForce(explosionPower,transform.position,explosionRadius);
}
}
}
}
Answer by excdu · Nov 19, 2012 at 12:02 AM
I figured it out. I had to have transform.position+Random.insideUnitSphere*explosionRadius as the explosion position, and increase the explosion force a bit.
For reference, here's the final code:
public class EnemyExplode : MonoBehaviour {
public float explosionRadius = 5f;
public float explosionPower = 1000f;
void OnTriggerEnter() {
foreach (Transform child in transform) {
child.rigidbody.useGravity = true;
child.rigidbody.AddExplosionForce(explosionPower,child.transform.position+Random.insideUnitSphere*explosionRadius,explosionRadius,3.0f);
}
collider.enabled = false;
}
}
Your answer
Follow this Question
Related Questions
Detach child and add force 0 Answers
Access Animation in child 1 Answer
Deactivate Specific Children In Partent 1 Answer
Detect collision with child object? 2 Answers
AddExplosionForce only goes up 0 Answers