| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class GlassBallBreak : MonoBehaviour
- {
- [Header("破碎参数")]
- public GameObject brokenPrefab; // 破碎后的碎片预制体
- public ParticleSystem breakEffect; // 破碎粒子特效
- public float explosionForce = 10f; // 碎片飞溅的爆炸力
- public float destroyDelay = 3f; // 碎片自动销毁时间
- public AudioClip breakSound; // 破碎音效
- private void OnMouseDown()
- {
- BreakGlass();
- }
- private void BreakGlass()
- {
- // 1. 生成破碎碎片
- if (brokenPrefab != null)
- {
- GameObject brokenGlass = Instantiate(brokenPrefab, transform.position, transform.rotation);
- AddExplosionForce(brokenGlass); // 为碎片添加爆炸力
- Destroy(brokenGlass, destroyDelay); // 延迟销毁碎片
- }
- // 2. 播放粒子特效
- if (breakEffect != null)
- {
- ParticleSystem effect = Instantiate(breakEffect, transform.position, Quaternion.identity);
- effect.Play();
- Destroy(effect.gameObject, effect.main.duration);
- }
- // 3. 播放音效
- if (breakSound != null)
- {
- AudioSource.PlayClipAtPoint(breakSound, transform.position);
- }
- // 4. 隐藏或销毁原物体
- gameObject.SetActive(false); // 或 Destroy(gameObject);
- }
- // 为所有碎片添加随机爆炸力
- private void AddExplosionForce(GameObject brokenObject)
- {
- Rigidbody[] rbs = brokenObject.GetComponentsInChildren<Rigidbody>();
- foreach (Rigidbody rb in rbs)
- {
- Vector3 randomDir = new Vector3(
- Random.Range(-1f, 1f),
- Random.Range(0.5f, 1f),
- Random.Range(-1f, 1f)
- ).normalized;
- rb.AddForce(randomDir * explosionForce, ForceMode.Impulse);
- rb.AddTorque(randomDir * explosionForce * 0.1f); // 添加旋转扭矩
- }
- }
- }
|