I set up an explosion in a unit, but I cannot remove objects within the radius of the explosion. How to write the Destroy function in the block for defining objects inside the radius so that these objects are deleted?
public void Explode()
{
Collider[] overlappedColliders = Physics.OverlapSphere(transform.position, Radius);
for(int i = 0; i < overlappedColliders.Length; i )
{
Rigidbody rigidbody = overlappedColliders[i].attachedRigidbody;
if(rigidbody)
{
rigidbody.AddExplosionForce(Force, transform.position, Radius, 1f);
Explosion explosion = rigidbody.GetComponent<Explosion>();
if(!explosion)
{
if(Vector3.Distance(transform.position, rigidbody.position) < Radius)
{
Destroy(explosion.gameObject);
}
}
}
}
}
public void OnCollisionEnter (Collision collision)
{
if(collision.gameObject.tag == "Explosion")
{
Explode();
Destroy(gameObject);
Instantiate(ExplosionEffect, transform.position, Quaternion.identity);
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, Radius);
}
CodePudding user response:
Hmm, in my opinion, make a gameobject that contains elements that is in the radius of the explosion, when the explosion happens you can destroy it immediately by referencing to that gameobject and destroy it
CodePudding user response:
You can try the following:
public void Explode()
{
//I left this part of your script since it adds a push effect to the objects caught in the explosion
Collider[] overlappedColliders = Physics.OverlapSphere(transform.position, Radius);
for(int i = 0; i < overlappedColliders.Length; i )
{
Rigidbody rigidbody = overlappedColliders[i].attachedRigidbody;
if(rigidbody)
{
rigidbody.AddExplosionForce(Force, transform.position, Radius, 1f);
}
}
//Now destroy the objects in the blast radius applying a delay based in distance
var detonationPoint = transform.position;
//filter the objects in the scene by distance and ignore the source gameobject
var objectsInExplosionRadius = FindObjectsOfType<GameObject>().Select(x => new
{
distance = Vector3.Distance(x.transform.position, detonationPoint),
obj = x
}).Where(x => x.distance <= Radius && !ReferenceEquals(x, gameObject));
foreach (var objectInRadius in objectsInExplosionRadius)
{
//apply the destruction delay as desired
Destroy(objectInRadius.obj, objectInRadius.distance);
}
}