Files
zeling_v2/Assets/_Game/Scripts/Player/PlayerCombat.cs
2026-05-19 11:50:21 +08:00

90 lines
3.5 KiB
C#

using UnityEngine;
using BaseGames.Combat;
namespace BaseGames.Player
{
/// <summary>
/// 玩家战斗组件。
/// HitBox 随装备武器动态实例化到 [WeaponSocket] 子节点,通过 WeaponManager.ActiveHitBoxInstance 访问。
/// </summary>
public class PlayerCombat : MonoBehaviour
{
[SerializeField] private WeaponManager _weaponManager;
private PlayerStats _stats;
private PlayerMovement _movement;
private WeaponHitBoxInstance _currentHitBoxInstance;
/// <summary>下劈 HitBox 命中确认事件(供 DownAttackState 订阅 pogo 弹跳逻辑)。</summary>
public event System.Action<DamageInfo> OnDownHitConfirmed;
private void Awake()
{
_stats = GetComponentInParent<PlayerStats>();
_movement = GetComponentInParent<PlayerMovement>();
}
private void OnEnable()
{
if (_weaponManager != null)
_weaponManager.OnWeaponChanged += HandleWeaponChanged;
}
private void OnDisable()
{
if (_weaponManager != null)
_weaponManager.OnWeaponChanged -= HandleWeaponChanged;
UnsubscribeDownHit();
}
private void HandleWeaponChanged(WeaponSO _)
{
UnsubscribeDownHit();
_currentHitBoxInstance = _weaponManager.ActiveHitBoxInstance;
if (_currentHitBoxInstance != null)
_currentHitBoxInstance.OnDownHitConfirmed += HandleDownHitConfirmed;
}
private void UnsubscribeDownHit()
{
if (_currentHitBoxInstance == null) return;
_currentHitBoxInstance.OnDownHitConfirmed -= HandleDownHitConfirmed;
_currentHitBoxInstance = null;
}
private void HandleDownHitConfirmed(DamageInfo info) => OnDownHitConfirmed?.Invoke(info);
// ── HitBox 激活(由 State / AnimationEvent 调用)─────────────────────
/// <summary>
/// 激活 HitBox。
/// hitBoxId 非空时按 Id 精确激活 Prefab 中对应子节点;空 = 方向默认。
/// source 为 null 时回退到 WeaponSO.GetSourceByDir(dir)(方向第 0 段)。
/// </summary>
public void EnableWeaponHitBox(AttackDirection dir,
string hitBoxId = "", DamageSourceSO source = null)
{
source ??= _weaponManager?.ActiveWeapon?.GetSourceByDir(dir);
_weaponManager?.ActiveHitBoxInstance?.Activate(dir, source, transform, hitBoxId);
}
public void DisableWeaponHitBox(AttackDirection dir)
=> _weaponManager?.ActiveHitBoxInstance?.Deactivate(dir);
public void DisableAllWeaponHitBoxes()
=> _weaponManager?.ActiveHitBoxInstance?.DeactivateAll();
/// <summary>命中确认回调:增加灵力(由 HurtBox.ReceiveDamage 步骤 7 的 HitConfirmed 事件订阅)。</summary>
public void OnHitConfirmed(DamageInfo info)
{
int gain = _weaponManager?.ActiveWeapon?.soulPowerGain ?? 10;
_stats?.AddSoulPower(gain);
// 攻击命中反嵈:向攻击反方向施加微小后退冲量,增强打击感
if (_movement?.Rb != null && info.KnockbackDirection.x != 0f)
_movement.Rb.AddForce(
new UnityEngine.Vector2(UnityEngine.Mathf.Sign(-info.KnockbackDirection.x) * 2f, 0f),
UnityEngine.ForceMode2D.Impulse);
}
}
}