using System.Collections; using System.Collections.Generic; using UnityEngine; public class RobotExplosion : MonoBehaviour { [Header("爆炸特效")] public GameObject explosionEffect; // 爆炸特效预制体 public float effectDuration = 2f; // 特效持续时间 [Header("碎片设置")] public GameObject[] debrisPrefabs; // 碎片预制体数组 public int debrisAmount = 20; // 碎片生成数量 public float minForce = 5f; // 最小爆炸力 public float maxForce = 15f; // 最大爆炸力 public float torqueIntensity = 50f; // 旋转强度 [Header("消失设置")] public float debrisLifeTime = 3f; // 碎片存在时间 public float fadeDuration = 0.5f; // 渐隐时间 private bool isExploded = false; private void OnMouseDown() { if (!isExploded) { StartExplosion(); isExploded = true; } } void StartExplosion() { // 生成爆炸特效 if (explosionEffect != null) { GameObject effect = Instantiate(explosionEffect, transform.position, Quaternion.identity); Destroy(effect, effectDuration); } // 生成随机碎片 for (int i = 0; i < debrisAmount; i++) { SpawnDebris(); } // 隐藏机器人 SetRobotVisible(false); } void SpawnDebris() { if (debrisPrefabs.Length == 0) return; // 随机选择碎片预制体 GameObject selectedDebris = debrisPrefabs[Random.Range(0, debrisPrefabs.Length)]; // 生成参数设置 Vector3 spawnPos = transform.position + Random.insideUnitSphere * 0.5f; Quaternion spawnRot = Random.rotation; GameObject debris = Instantiate(selectedDebris, spawnPos, spawnRot); // 添加物理组件 Rigidbody rb = debris.GetComponent(); if (rb == null) rb = debris.AddComponent(); // 施加随机方向力 Vector3 randomDir = new Vector3( Random.Range(-1f, 1f), Random.Range(0.5f, 1f), Random.Range(-1f, 1f) ).normalized; float force = Random.Range(minForce, maxForce); rb.AddForce(randomDir * force, ForceMode.Impulse); // 添加随机旋转 rb.AddTorque( Random.insideUnitSphere * torqueIntensity, ForceMode.Impulse ); // 自动销毁 StartCoroutine(DestroyDebris(debris)); } System.Collections.IEnumerator DestroyDebris(GameObject debris) { yield return new WaitForSeconds(debrisLifeTime - fadeDuration); // 渐隐效果 Renderer[] renderers = debris.GetComponentsInChildren(); float timer = 0f; while (timer < fadeDuration) { timer += Time.deltaTime; float alpha = Mathf.Lerp(1, 0, timer / fadeDuration); foreach (Renderer r in renderers) { if (r.material.HasProperty("_Color")) { Color color = r.material.color; color.a = alpha; r.material.color = color; } } yield return null; } Destroy(debris); } void SetRobotVisible(bool visible) { // 禁用所有渲染器和碰撞体 foreach (Renderer r in GetComponentsInChildren()) { r.enabled = visible; } foreach (Collider c in GetComponentsInChildren()) { c.enabled = visible; } } }