using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExplosionEffect : MonoBehaviour { [Header("爆炸碎片设置")] public GameObject[] debrisPrefabs; // 可替换的碎片预制体 public int debrisCount = 15; // 生成碎片数量 public float minForce = 5f; // 最小爆炸力 public float maxForce = 15f; // 最大爆炸力 [Header("随机化设置")] public float rotationIntensity = 50f; // 旋转强度 public Vector3 forceVariation = new Vector3(0.5f, 1f, 0.5f); // 方向随机化系数 [Header("特效设置")] public float lifeTime = 3f; // 碎片存在时间 public float fadeOutTime = 0.5f; // 渐隐时间 private void OnMouseDown() { // 禁用原始物体 GetComponent().enabled = false; GetComponent().enabled = false; // 生成随机碎片 for (int i = 0; i < debrisCount; i++) { CreateDebris(); } // 销毁原始物体(带延迟) Destroy(gameObject, lifeTime); } void CreateDebris() { // 随机选择预制体 GameObject debris = Instantiate( debrisPrefabs[Random.Range(0, debrisPrefabs.Length)], transform.position + Random.insideUnitSphere * 0.5f, Random.rotation ); // 添加物理组件 Rigidbody rb = debris.GetComponent(); if (rb == null) rb = debris.AddComponent(); // 计算随机爆炸方向 Vector3 randomDirection = new Vector3( Random.Range(-forceVariation.x, forceVariation.x), Random.Range(0, forceVariation.y), Random.Range(-forceVariation.z, forceVariation.z) ).normalized; // 施加爆炸力 float randomForce = Random.Range(minForce, maxForce); rb.AddForce(randomDirection * randomForce, ForceMode.Impulse); // 添加随机旋转 rb.AddTorque( Random.insideUnitSphere * rotationIntensity, ForceMode.Impulse ); // 配置自动销毁 StartCoroutine(FadeOutDebris(debris)); } System.Collections.IEnumerator FadeOutDebris(GameObject debris) { // 获取所有子物体渲染器 Renderer[] renderers = debris.GetComponentsInChildren(); float timer = 0; while (timer < fadeOutTime) { timer += Time.deltaTime; float alpha = Mathf.Lerp(1, 0, timer / fadeOutTime); foreach (Renderer r in renderers) { if (r.material.HasProperty("_Color")) { Color c = r.material.color; c.a = alpha; r.material.color = c; } } yield return null; } Destroy(debris); } }