using BaseGames.Player; using UnityEngine; namespace BaseGames.World { /// /// 危险区域。玩家进入时触发即死(调用 Kill(),无视无敌帧)或持续伤害。 /// [RequireComponent(typeof(Collider2D))] public class HazardZone : MonoBehaviour { [SerializeField] private bool _isInstantKill = true; [SerializeField] private int _damage = 1; [Tooltip("持续伤害模式下每次造成伤害的间隔(秒)。仅 _isInstantKill = false 时生效。")] [SerializeField] private float _damageInterval = 0.5f; private PlayerStats _cachedStats; private float _damageTimer; private bool _playerInside; private void OnTriggerEnter2D(Collider2D other) { if (!other.CompareTag("Player")) return; _cachedStats = other.GetComponentInParent(); if (_cachedStats == null) return; _playerInside = true; ApplyDamage(); _damageTimer = _damageInterval; } private void OnTriggerExit2D(Collider2D other) { if (!other.CompareTag("Player")) return; _playerInside = false; _cachedStats = null; } private void Update() { if (!_playerInside || _isInstantKill || _cachedStats == null) return; _damageTimer -= Time.deltaTime; if (_damageTimer <= 0f) { ApplyDamage(); _damageTimer = _damageInterval; } } private void ApplyDamage() { if (_cachedStats == null) return; if (_isInstantKill) _cachedStats.Kill(); else _cachedStats.TakeDamage(_damage); } private void OnDrawGizmos() { var col = GetComponent(); if (col == null) return; Gizmos.color = new Color(1f, 0f, 0f, 0.3f); Gizmos.DrawCube(transform.position, col.bounds.size); Gizmos.color = new Color(1f, 0f, 0f, 0.8f); Gizmos.DrawWireCube(transform.position, col.bounds.size); } } }