ExplosionOnClick.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class ExplosionOnClick : MonoBehaviour
  5. {
  6. [Header("Settings")]
  7. public GameObject explosionEffect; // 爆炸特效预制体
  8. public float explosionRadius = 5f; // 爆炸影响范围
  9. public float explosionForce = 700f; // 爆炸力度
  10. public float damage = 50f; // 爆炸伤害值
  11. public LayerMask affectedLayers; // 受影响的层级
  12. void Update()
  13. {
  14. if (Input.GetMouseButtonDown(0))
  15. {
  16. CreateExplosion();
  17. }
  18. }
  19. void CreateExplosion()
  20. {
  21. // 通过射线检测获取鼠标点击位置
  22. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  23. if (Physics.Raycast(ray, out RaycastHit hit))
  24. {
  25. // 实例化爆炸特效
  26. if (explosionEffect != null)
  27. {
  28. GameObject effect = Instantiate(
  29. explosionEffect,
  30. hit.point,
  31. Quaternion.identity
  32. );
  33. Destroy(effect, 2f); // 2秒后自动销毁特效
  34. }
  35. // 检测爆炸范围内的碰撞体
  36. Collider[] colliders = Physics.OverlapSphere(
  37. hit.point,
  38. explosionRadius,
  39. affectedLayers
  40. );
  41. foreach (Collider hitCollider in colliders)
  42. {
  43. // 施加物理力
  44. Rigidbody rb = hitCollider.GetComponent<Rigidbody>();
  45. if (rb != null)
  46. {
  47. rb.AddExplosionForce(
  48. explosionForce,
  49. hit.point,
  50. explosionRadius,
  51. 3f,
  52. ForceMode.Impulse
  53. );
  54. }
  55. // 造成伤害(可选)
  56. // Health health = hitCollider.GetComponent<Health>();
  57. // if (health != null)
  58. // {
  59. // float distance = Vector3.Distance(hit.point, hitCollider.transform.position);
  60. // float damageMultiplier = 1 - Mathf.Clamp01(distance / explosionRadius);
  61. // health.TakeDamage(damage * damageMultiplier);
  62. // }
  63. }
  64. }
  65. }
  66. // 在Scene视图中显示爆炸范围
  67. void OnDrawGizmosSelected()
  68. {
  69. Gizmos.color = Color.red;
  70. Gizmos.DrawWireSphere(transform.position, explosionRadius);
  71. }
  72. }