GlassBallBreak.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class GlassBallBreak : MonoBehaviour
  5. {
  6. [Header("破碎参数")]
  7. public GameObject brokenPrefab; // 破碎后的碎片预制体
  8. public ParticleSystem breakEffect; // 破碎粒子特效
  9. public float explosionForce = 10f; // 碎片飞溅的爆炸力
  10. public float destroyDelay = 3f; // 碎片自动销毁时间
  11. public AudioClip breakSound; // 破碎音效
  12. private void OnMouseDown()
  13. {
  14. BreakGlass();
  15. }
  16. private void BreakGlass()
  17. {
  18. // 1. 生成破碎碎片
  19. if (brokenPrefab != null)
  20. {
  21. GameObject brokenGlass = Instantiate(brokenPrefab, transform.position, transform.rotation);
  22. AddExplosionForce(brokenGlass); // 为碎片添加爆炸力
  23. Destroy(brokenGlass, destroyDelay); // 延迟销毁碎片
  24. }
  25. // 2. 播放粒子特效
  26. if (breakEffect != null)
  27. {
  28. ParticleSystem effect = Instantiate(breakEffect, transform.position, Quaternion.identity);
  29. effect.Play();
  30. Destroy(effect.gameObject, effect.main.duration);
  31. }
  32. // 3. 播放音效
  33. if (breakSound != null)
  34. {
  35. AudioSource.PlayClipAtPoint(breakSound, transform.position);
  36. }
  37. // 4. 隐藏或销毁原物体
  38. gameObject.SetActive(false); // 或 Destroy(gameObject);
  39. }
  40. // 为所有碎片添加随机爆炸力
  41. private void AddExplosionForce(GameObject brokenObject)
  42. {
  43. Rigidbody[] rbs = brokenObject.GetComponentsInChildren<Rigidbody>();
  44. foreach (Rigidbody rb in rbs)
  45. {
  46. Vector3 randomDir = new Vector3(
  47. Random.Range(-1f, 1f),
  48. Random.Range(0.5f, 1f),
  49. Random.Range(-1f, 1f)
  50. ).normalized;
  51. rb.AddForce(randomDir * explosionForce, ForceMode.Impulse);
  52. rb.AddTorque(randomDir * explosionForce * 0.1f); // 添加旋转扭矩
  53. }
  54. }
  55. }