attach the Throw script to the MainCamera of a character controller
In your scripts:
//ThrowScript.js which is attached to the MainCamera
var explosionPower: float = 2000.0;
var grenadePrefab : Transform;
function Update ()
{
//left mouse button is pressed
if (Input.GetButtonDown("Fire1"))
{
//create grenade prefab
var grenade = Instantiate(grenadePrefab, transform.position, Quaternion.identity);
//throw the grenade by adding the forward force
grenade.rigidbody.AddForce(transform.forward * explosionPower);
}
}
Grenade script which is attached to the GrenadePrefab
//GrenadeScript.js
var explosionTime: float = 2.0;
var explosionRadius: float = 5.0;
var explosionDistane: float = 10.0;
var explosionPower: float = 2000.0;
var explosionPrefab: Transform;
function Awake()
{
explosionTime = Time.time;
}
function Update()
{
//delay grenade explosion
if (Time.time > explosionTime + 2)
{
//create the explosion
Instantiate(explosionPrefab, transform.position, Quaternion.identity);
//find all nearby colliders
//use the statement below
//var colliders : Collider[] = Physics.OverlapSphere(transform.position, explosionRadius);
//or use the statement below
var hit: RaycastHit[] = Physics.SphereCastAll(transform.position, explosionRadius, transform.up, explosionDistane);
//apply a force to all surrounding rigid bodies
for( var hitObject in hit)
{
//check to make sure to apply force to only a game object that has rigid body component
if (hitObject.rigidbody)
{
hitObject.rigidbody.AddExplosionForce(explosionPower, transform.position, explosionRadius);
}
}
Destroy(gameObject);
}
}
Make sure that you assign grenadePrefab and explosionPrefab in the property Inspector.
Well, I do not understand all the details of the SphereCastAll function. However, according to the Unity document:
ExplosionRadius (Radius) is the radius of the sphere.
ExplosionDistance (Distance) is th length of the sweep.
The sweep (Distance) starts from a center of a sphere; therefore, technically you can set Radius to zero and Distance to 10 unit and it still does the same thing.
Sorry to revive an old thread but in case it’s helpful to other developers, I believe the ‘Cast’ functions will not return objects that collide with the collider function in its initial position (overlap).
For example, for SphereCastAll, the initial space occupied by the sphere is ignored - only collisions that occur while the sphere is traveling (cast) will be taken into account.