如何移除爆炸半径内的物体?

  • 本文关键字:何移 c# unity-game-engine
  • 更新时间 :
  • 英文 :


我在一个单位内设置了一个爆炸,但是我不能移除爆炸半径内的物体。如何在定义半径内的对象的块中编写Destroy函数,以便删除这些对象?

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);
}

在我看来,制作一个包含爆炸半径内元素的游戏对象,当爆炸发生时,你可以通过引用该游戏对象立即摧毁它

您可以尝试以下操作:

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);
}
}

相关内容

  • 没有找到相关文章

最新更新