| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class ExplosionOnClick : MonoBehaviour
- {
- [Header("Settings")]
- public GameObject explosionEffect; // 爆炸特效预制体
- public float explosionRadius = 5f; // 爆炸影响范围
- public float explosionForce = 700f; // 爆炸力度
- public float damage = 50f; // 爆炸伤害值
- public LayerMask affectedLayers; // 受影响的层级
- void Update()
- {
- if (Input.GetMouseButtonDown(0))
- {
- CreateExplosion();
- }
- }
- void CreateExplosion()
- {
- // 通过射线检测获取鼠标点击位置
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ray, out RaycastHit hit))
- {
- // 实例化爆炸特效
- if (explosionEffect != null)
- {
- GameObject effect = Instantiate(
- explosionEffect,
- hit.point,
- Quaternion.identity
- );
- Destroy(effect, 2f); // 2秒后自动销毁特效
- }
- // 检测爆炸范围内的碰撞体
- Collider[] colliders = Physics.OverlapSphere(
- hit.point,
- explosionRadius,
- affectedLayers
- );
- foreach (Collider hitCollider in colliders)
- {
- // 施加物理力
- Rigidbody rb = hitCollider.GetComponent<Rigidbody>();
- if (rb != null)
- {
- rb.AddExplosionForce(
- explosionForce,
- hit.point,
- explosionRadius,
- 3f,
- ForceMode.Impulse
- );
- }
- // 造成伤害(可选)
- // Health health = hitCollider.GetComponent<Health>();
- // if (health != null)
- // {
- // float distance = Vector3.Distance(hit.point, hitCollider.transform.position);
- // float damageMultiplier = 1 - Mathf.Clamp01(distance / explosionRadius);
- // health.TakeDamage(damage * damageMultiplier);
- // }
- }
- }
- }
- // 在Scene视图中显示爆炸范围
- void OnDrawGizmosSelected()
- {
- Gizmos.color = Color.red;
- Gizmos.DrawWireSphere(transform.position, explosionRadius);
- }
- }
|