58 lines
1.9 KiB
C#
58 lines
1.9 KiB
C#
using UnityEngine;
|
|
|
|
public class ExplosionEffect : MonoBehaviour
|
|
{
|
|
[Header("爆炸设置")]
|
|
public float explosionForce = 10f; // 爆炸力度
|
|
public float explosionRadius = 5f; // 爆炸范围
|
|
public float upwardForce = -5f; // 向上的力
|
|
public float destroyDelay = 10f; // 碎片销毁延迟
|
|
public float rotationForce = 5f; // 旋转力度
|
|
|
|
private void Awake()
|
|
{
|
|
// 获取所有子物体的Rigidbody组件
|
|
Rigidbody[] fragments = GetComponentsInChildren<Rigidbody>();
|
|
|
|
// 计算所有碎片的中心点
|
|
Vector3 centerPoint = Vector3.zero;
|
|
foreach (Rigidbody fragment in fragments)
|
|
{
|
|
if (fragment != null)
|
|
{
|
|
centerPoint += fragment.transform.position;
|
|
}
|
|
}
|
|
centerPoint /= fragments.Length;
|
|
|
|
foreach (Rigidbody fragment in fragments)
|
|
{
|
|
// 确保每个碎片都有Rigidbody组件
|
|
if (fragment != null)
|
|
{
|
|
// 添加爆炸力,使用计算出的中心点
|
|
fragment.AddExplosionForce(
|
|
explosionForce,
|
|
centerPoint,
|
|
explosionRadius,
|
|
upwardForce,
|
|
ForceMode.Impulse
|
|
);
|
|
|
|
// 添加随机旋转
|
|
Vector3 randomRotation = new Vector3(
|
|
Random.Range(-rotationForce, rotationForce),
|
|
Random.Range(-rotationForce, rotationForce),
|
|
Random.Range(-rotationForce, rotationForce)
|
|
);
|
|
fragment.AddTorque(randomRotation, ForceMode.Impulse);
|
|
|
|
// 延迟销毁碎片
|
|
Destroy(fragment.gameObject, destroyDelay);
|
|
}
|
|
}
|
|
|
|
// 销毁父物体
|
|
Destroy(gameObject, destroyDelay);
|
|
}
|
|
} |