ExplosionEffect.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class ExplosionEffect : MonoBehaviour
  5. {
  6. [Header("爆炸碎片设置")]
  7. public GameObject[] debrisPrefabs; // 可替换的碎片预制体
  8. public int debrisCount = 15; // 生成碎片数量
  9. public float minForce = 5f; // 最小爆炸力
  10. public float maxForce = 15f; // 最大爆炸力
  11. [Header("随机化设置")]
  12. public float rotationIntensity = 50f; // 旋转强度
  13. public Vector3 forceVariation = new Vector3(0.5f, 1f, 0.5f); // 方向随机化系数
  14. [Header("特效设置")]
  15. public float lifeTime = 3f; // 碎片存在时间
  16. public float fadeOutTime = 0.5f; // 渐隐时间
  17. private void OnMouseDown()
  18. {
  19. // 禁用原始物体
  20. GetComponent<Renderer>().enabled = false;
  21. GetComponent<Collider>().enabled = false;
  22. // 生成随机碎片
  23. for (int i = 0; i < debrisCount; i++)
  24. {
  25. CreateDebris();
  26. }
  27. // 销毁原始物体(带延迟)
  28. Destroy(gameObject, lifeTime);
  29. }
  30. void CreateDebris()
  31. {
  32. // 随机选择预制体
  33. GameObject debris = Instantiate(
  34. debrisPrefabs[Random.Range(0, debrisPrefabs.Length)],
  35. transform.position + Random.insideUnitSphere * 0.5f,
  36. Random.rotation
  37. );
  38. // 添加物理组件
  39. Rigidbody rb = debris.GetComponent<Rigidbody>();
  40. if (rb == null) rb = debris.AddComponent<Rigidbody>();
  41. // 计算随机爆炸方向
  42. Vector3 randomDirection = new Vector3(
  43. Random.Range(-forceVariation.x, forceVariation.x),
  44. Random.Range(0, forceVariation.y),
  45. Random.Range(-forceVariation.z, forceVariation.z)
  46. ).normalized;
  47. // 施加爆炸力
  48. float randomForce = Random.Range(minForce, maxForce);
  49. rb.AddForce(randomDirection * randomForce, ForceMode.Impulse);
  50. // 添加随机旋转
  51. rb.AddTorque(
  52. Random.insideUnitSphere * rotationIntensity,
  53. ForceMode.Impulse
  54. );
  55. // 配置自动销毁
  56. StartCoroutine(FadeOutDebris(debris));
  57. }
  58. System.Collections.IEnumerator FadeOutDebris(GameObject debris)
  59. {
  60. // 获取所有子物体渲染器
  61. Renderer[] renderers = debris.GetComponentsInChildren<Renderer>();
  62. float timer = 0;
  63. while (timer < fadeOutTime)
  64. {
  65. timer += Time.deltaTime;
  66. float alpha = Mathf.Lerp(1, 0, timer / fadeOutTime);
  67. foreach (Renderer r in renderers)
  68. {
  69. if (r.material.HasProperty("_Color"))
  70. {
  71. Color c = r.material.color;
  72. c.a = alpha;
  73. r.material.color = c;
  74. }
  75. }
  76. yield return null;
  77. }
  78. Destroy(debris);
  79. }
  80. }