Game Development Reference
In-Depth Information
6.
Save the script.
7.
Click Play, and test the explosion to make sure it continues to work as
before.
To calculate the effects of the “blast,” you will require a few new variables.
8.
Add the following variables:
public float explosionTime = 1f; // how long the effect will last
public float explosionRadius = 0.5f; // the radius of the effect
public float explosionPower = 50f; // the force that will be applied to nearby objects
public int damage = 10; // the point amount of damage delivered
On the off chance you want to adjust the variable's values, you will have to do so by selecting the
PotatoAmmo object in the Prefabs folder.
Beneath the Instantiate line, add the following:
9.
// Find all nearby colliders and put them into an array
Collider[] hitColliders = Physics.OverlapSphere (transform.position,explosionRadius);
In this line, you are declaring a variable of an array of Colliders and filling it using the Physics
function or method, OverlapSphere() . Every object with a collider that is intersected by the sphere
will be added to the array. Armed with the objects within range that have a collider and using a
foreach loop, you will apply a force if they have a Rigidbody component and send a message to
destroy any with the appropriate receiver script.
Add the following code beneath the Collider[] line:
10.
// Apply a force to all surrounding rigid bodies & destroy anything with a Terminator
function
foreach (Collider hit in hitColliders) {
// Tell the rigidbody or any other script attached to it that the object was hit,
// via the Terminator script
hit.gameObject.SendMessage ("Terminator", damage, SendMessageOptions.
DontRequireReceiver);
if (hit.rigidbody){ // if it has a rigidbody...
hit.rigidbody.AddExplosionForce(explosionPower, transform.
position,explosionRadius);
}
}
The last line sends a message [calls] any function by the name of “Terminator” on any of the object's
scripts. In a more complicated version of the Explosion script, you could calculate a damage
according to the distance from the explosion point. In this simple variation, you will send a hit
damage amount just to see how it works. The function name to call is mandatory, but an argument
and option message are optional. DontRequireReceiver prevents an error message if the object
doesn't have a script with a Terminator function.
11.
Save the script.
 
Search WWH ::




Custom Search