yyl
5 天以前 c124d98bdf9659cf764bebb799bee42c30eb152f
Main/System/Battle/Skill/SkillBase.cs
@@ -1,488 +1,705 @@
using System.Collections.Generic;
using UnityEngine;
using System;
using DG.Tweening;
using Spine;
using System.Linq;
using System;
public class SkillBase
{
   protected HB427_tagSCUseSkill tagUseSkillAttack;
    const float moveTime = 0.5f;
   protected SkillConfig skillConfig;
    protected SkillEffect skillEffect;
    protected HB427_tagSCUseSkill tagUseSkillAttack;
    public SkillConfig skillConfig;
    protected bool isFinished = false;
    protected BattleField battleField = null; // 战场
    protected RectTransform targetNode = null; // 目标节点
    protected BattleObject caster = null; // 施法者
    protected List<GameNetPackBasic> packList;
    protected List<SkillRecordAction> otherSkillActionList = new List<SkillRecordAction>();
    protected List<H0704_tagRolePackRefresh> dropPackList = new List<H0704_tagRolePackRefresh>();
    protected List<HB405_tagMCAddExp> expPackList = new List<HB405_tagMCAddExp>();
    protected bool moveFinished = false;
    public int fromSkillId;
    public bool isPlay = false;
   protected bool isFinished = false;
    private Dictionary<int, BattleDrops> tempDropList = new Dictionary<int, BattleDrops>();
    private Dictionary<int, HB422_tagMCTurnFightObjDead> tempDeadPackList = new Dictionary<int, HB422_tagMCTurnFightObjDead>();
   protected BattleField battleField = null; // 战场
    // 构造函数:初始化技能基础数据
    public SkillBase(BattleObject _caster, SkillConfig _skillCfg, HB427_tagSCUseSkill vNetData, List<GameNetPackBasic> _packList, BattleField _battleField = null)
    {
        caster = _caster;
        if (null == caster)
        {
            throw new Exception("SkillBase caster is null ");
        }
        skillConfig = _skillCfg;
        tagUseSkillAttack = vNetData;
        battleField = _battleField;
        packList = _packList;
    }
   protected RectTransform targetNode = null; // 目标节点
    // 技能运行主逻辑:处理技能效果和其他技能动作
    public virtual void Run()
    {
        if (skillEffect != null)
        {
            if (skillEffect.IsFinished())
            {
                skillEffect = null;
                OnSkillFinished();
            }
            else
            {
                skillEffect.Run();
            }
            return;
        }
   protected BattleObject caster = null; // 施法者
        if (otherSkillActionList.Count > 0)
        {
            for (int i = otherSkillActionList.Count - 1; i >= 0; i--)
            {
                var action = otherSkillActionList[i];
                if (action.IsFinished())
                {
                    otherSkillActionList.RemoveAt(i);
                    OnSkillFinished();
                }
                else if (moveFinished)
                {
                    action.Run();
                }
            }
        }
    }
   protected bool startCounting = false;
    // 技能释放主逻辑:广播事件、高亮目标、执行释放
    public virtual void Cast()
    {
        // 广播技能释放事件
        string guid = battleField.guid;
        TeamHero teamHero = caster.teamHero;
        EventBroadcast.Instance.Broadcast<string, SkillConfig, TeamHero>(EventName.BATTLE_CAST_SKILL, guid, skillConfig, teamHero);
   protected bool pauseState = false;
        // 高亮所有本次技能相关的目标
        HighLightAllTargets();
   protected int curFrame = 0;
        // 根据释放模式执行相应逻辑
        switch (skillConfig.castMode)
        {
            case SkillCastMode.Self:
                CastImpl(OnAttackFinish);
                break;
            case SkillCastMode.Enemy:
                CastToEnemy();
                break;
            case SkillCastMode.Target:
                CastToTarget();
                break;
            case SkillCastMode.Allies:
                CastToAllies();
                break;
            case SkillCastMode.DashCast:
                DashCast(OnAttackFinish);
                break;
            default:
                Debug.LogError("强制结束技能 暂时不支持其他的方式释放 有需求please联系策划 技能id:" + skillConfig.SkillID + " cast position " + skillConfig.CastPosition);
                ForceFinished();
                break;
        }
    }
   protected List<GameNetPackBasic> packList;
    // 冲撞攻击模式(待实现)
    protected void DashCast(Action _onComplete)
    {
        Debug.LogError("DashCast 还没实现");
        ForceFinished();
    }
   protected SkillRecordAction otherSkillAction;
    // 对敌方释放技能:移动到敌方区域进行攻击
    protected void CastToEnemy()
    {
        RectTransform target = battleField.GetTeamNode(caster.GetEnemyCamp(), skillConfig);
        ExecuteMoveAndCastSequence(target, () =>
        {
            MoveToTarget(battleField.GetTeamNode(caster.Camp, caster.teamHero.positionNum), Vector2.zero, OnAttackFinish, 750F);
        });
    }
   protected List<H0704_tagRolePackRefresh> dropPackList = new List<H0704_tagRolePackRefresh>();
    // 对指定目标释放技能:移动到主要目标位置进行攻击
    protected void CastToTarget()
    {
        if (tagUseSkillAttack.HurtCount <= 0)
        {
            Debug.LogError("技能攻击包没有目标 HurtCount <= 0");
            OnSkillFinished();
            return;
        }
   protected List<HB405_tagMCAddExp> expPackList = new List<HB405_tagMCAddExp>();
        int mainTargetPosNum = BattleUtility.GetMainTargetPositionNum(caster, tagUseSkillAttack.HurtList.ToList(), skillConfig);
        BattleCamp battleCamp = skillConfig.TagFriendly != 0 ? caster.Camp : caster.GetEnemyCamp();
        RectTransform targetTrans = battleField.GetTeamNode(battleCamp, mainTargetPosNum);
   public SkillBase(BattleObject _caster, SkillConfig _skillCfg, HB427_tagSCUseSkill vNetData, List<GameNetPackBasic> _packList, BattleField _battleField = null)
   {
      caster = _caster;
      skillConfig = _skillCfg;
      tagUseSkillAttack = vNetData;
      battleField = _battleField;
      packList = _packList;
        ExecuteMoveAndCastSequence(targetTrans, () =>
        {
            RectTransform rectTransform = battleField.GetTeamNode(caster.Camp, caster.teamHero.positionNum);
            MoveToTarget(rectTransform, Vector2.zero, OnAttackFinish, 750F);
        });
    }
   }
    // 对友方释放技能:移动到友方区域进行治疗或增益
    protected void CastToAllies()
    {
        RectTransform target = battleField.GetTeamNode(caster.Camp, skillConfig);
        ExecuteMoveAndCastSequence(target, () =>
        {
            MoveToTarget(battleField.GetTeamNode(caster.Camp, caster.teamHero.positionNum), Vector2.zero, OnAttackFinish, 750F);
        });
    }
   public virtual void Run()
   {
      if (startCounting)
      {
         curFrame++;
      }
    // 执行移动-施法-返回序列:通用的移动攻击流程
    private void ExecuteMoveAndCastSequence(RectTransform target, Action onReturnComplete)
    {
        MoveToTarget(target, new Vector2(skillConfig.CastDistance, 0), () =>
        {
            TurnBack(() =>
            {
                CastImpl(() =>
                {
                    TurnBack(() =>
                    {
                        try
                        {
                            onReturnComplete?.Invoke(); // 添加异常处理防止回调异常导致状态不完整
                        }
                        catch (Exception ex)
                        {
                            Debug.LogError($"ExecuteMoveAndCastSequence回调异常: {ex.Message}");
                            throw;
                        }
                    }, -1f);
                });
            }, -1f);
        });
    }
      if (otherSkillAction != null)
      {
         if (otherSkillAction.IsFinished())
         {
            otherSkillAction = null;
            OnSkillFinished();
         }
         else
         {
            otherSkillAction.Run();
         }
      }
   }
    // 移动到目标位置:处理角色的移动动画和逻辑
    protected void MoveToTarget(RectTransform target, Vector2 offset, Action _onComplete = null, float speed = 500f)
    {
        if (skillConfig.CastDistance >= 9999)
        {
            _onComplete?.Invoke();
            return;
        }
        caster.motionBase.PlayAnimation(MotionName.run, true);
        var tweener = BattleUtility.MoveToTarget(caster.heroRectTrans, target, offset, () =>
        {
            caster.motionBase.PlayAnimation(MotionName.idle, true);
            _onComplete?.Invoke();
        }, speed);
        battleField.battleTweenMgr.OnPlayTween(tweener);
    }
   protected virtual void OnActiveSkillFrame()
   {
    // 转身逻辑:根据技能配置处理角色转向
    protected void TurnBack(Action _onComplete, float forward)
    {
        if (skillConfig.CastDistance < 0)
        {
            Vector3 scale = caster.heroGo.transform.localScale;
            scale.x = Mathf.Abs(scale.x) * forward;
            caster.heroGo.transform.localScale = scale;
        }
        _onComplete?.Invoke();
    }
   }
    // 攻击完成后的处理:转身、恢复状态、播放待机动画
    protected void OnAttackFinish()
    {
        TurnBack(null, 1f);
        OnAllAttackMoveFinished();
        caster.motionBase.PlayAnimation(MotionName.idle, true);
    }
   protected virtual void OnStartSkillFrame()
   {
    // 所有攻击移动完成后的处理:恢复UI显示状态
    protected virtual void OnAllAttackMoveFinished()
    {
        moveFinished = true;
        List<BattleObject> allList = battleField.battleObjMgr.allBattleObjDict.Values.ToList<BattleObject>();
        foreach (BattleObject bo in allList)
        {
            bo.layerMgr.SetFront();
            bo.heroInfoBar.SetActive(true);
        }
        battleField.battleRootNode.skillMaskNode.SetActive(false);
    }
   }
    // 执行技能释放动画和逻辑:播放施法动作并提供回调
    protected TrackEntry CastImpl(Action onComplete = null)
    {
        return caster.motionBase.PlaySkillAnimation(skillConfig, this, tagUseSkillAttack.BattleType == 4, onComplete);
    }
   protected virtual void OnEndSkillFrame()
   {
   }
    // 技能开始回调:处理死亡、子技能、技能效果初始化
    public void OnSkillStart()
    {
        HandleDead();
        skillEffect = SkillEffectFactory.CreateSkillEffect(caster, skillConfig, tagUseSkillAttack);
        skillEffect.Play(OnHitTargets);
        foreach (var subSkillPack in tagUseSkillAttack.subSkillList)
        {
            SkillRecordAction recordAction = CustomHB426CombinePack.CreateSkillAction(battleField.guid, new List<GameNetPackBasic>() { subSkillPack });
            otherSkillActionList.Add(recordAction);
            battleField.recordPlayer.ImmediatelyPlay(recordAction);
        }
        isPlay = true;
    }
   public void Pause()
   {
      pauseState = startCounting;
      startCounting = false;
   }
    // 技能前摇结束回调
    public virtual void OnStartSkillFrameEnd() { }
   public void Resume()
   {
      startCounting = pauseState;
   }
    // 技能中摇开始回调:通知技能效果处理中摇开始
    public virtual void OnMiddleFrameStart(int times)
    {
        skillEffect?.OnMiddleFrameStart(times); // 修复:添加空值检查
    }
   // 0·移动到距离目标n码,的距离释放(可配置,9999即原地释放,负数则是移动到人物背面,人物要转身)
   // 1·移动到距离阵容位置n码的距离(如2号位,5号位)释放(即战场中央此类)
   public virtual void Cast()
   {
      //   高亮所有本次技能相关的目标
      HighLightAllTargets();
    // 技能中摇结束回调:通知技能效果处理中摇结束
    public virtual void OnMiddleFrameEnd(int times, int hitIndex)
    {
        skillEffect?.OnMiddleFrameEnd(times, hitIndex); // 修复:添加空值检查
    }
      //   距离配成负数要转身 TurnBack
    // 技能后摇开始回调:通知技能效果处理后摇开始
    public virtual void OnFinalFrameStart()
    {
        skillEffect?.OnFinalFrameStart(); // 修复:添加空值检查
    }
      switch (skillConfig.castMode)
      {
         case SkillCastMode.Self:
            PlayCastAnimation(() => DoSkillLogic(OnSkillFinished));
            break;
         case SkillCastMode.Enemy:
            MoveToTarget(caster.GetEnemyCamp(), skillConfig, _onComplete: () => TurnBack(() => PlayCastAnimation(() => DoSkillLogic(() => { BackToOrigin(OnSkillFinished); }))));
            break;
         case SkillCastMode.Target:
            // 目标是敌方主目标
            if (tagUseSkillAttack.HurtCount <= 0)
            {
               Debug.LogError("技能攻击包没有目标 HurtCount <= 0");
               OnSkillFinished();
               return;
            }
    // 技能后摇结束回调:通知技能效果处理后摇结束
    public virtual void OnFinalFrameEnd()
    {
        skillEffect?.OnFinalFrameEnd(); // 修复:添加空值检查
    }
            var mainHurt = tagUseSkillAttack.HurtList[0];
    // 高亮所有相关目标:设置施法者和目标的显示层级
    protected void HighLightAllTargets()
    {
        caster.layerMgr.SetSortingOrder(BattleConst.ActiveHeroActionSortingOrder);
            BattleObject mainTarget = battleField.battleObjMgr.GetBattleObject((int)mainHurt.ObjID);
            if (mainTarget == null)
            {
               Debug.LogError("目标为空 mainTarget == null ObjID : " + mainHurt.ObjID);
               OnSkillFinished();
               return;
            }
            MoveToTarget(mainTarget.Camp, mainTarget, _onComplete: () => TurnBack(() => PlayCastAnimation(() => DoSkillLogic(() => { BackToOrigin(OnSkillFinished); }))));
            break;
         case SkillCastMode.Allies:
            MoveToTarget(caster.Camp, skillConfig, _onComplete: () => TurnBack(() => PlayCastAnimation(() => DoSkillLogic(() => { BackToOrigin(OnSkillFinished); }))));
            break;
         // case SkillCastMode.DashCast:
         //    DashToTarget(() => BackToOrigin(OnSkillFinished));
         //    break;
         default:
            Debug.LogError("暂时不支持其他的方式释放 有需求请联系策划" + skillConfig.SkillID);
            OnSkillFinished();
            break;
      }
   }
        if (skillConfig.FuncType != 2)
            return;
   //   冲刺的技能 动作 跟移动 是同时进行的 移动到目标的一瞬间就要进行技能逻辑
   // protected void DashToTarget(Action _onComplete)
   // {
   //    TrackEntry entry = PlayCastAnimation();
   //    BattleObject mainTarget = battleField.battleObjMgr.GetBattleObject((int)tagUseSkillAttack.AttackID);
   //    if (mainTarget == null)
   //    {
   //       Debug.LogError("目标为空 mainTarget == null AttackID : " + tagUseSkillAttack.AttackID);
   //       _onComplete?.Invoke();
   //       return;
   //    }
        List<BattleObject> targetList = battleField.battleObjMgr.GetBattleObjList(tagUseSkillAttack);
        List<BattleObject> highlightList = new List<BattleObject>(targetList) { caster };
        List<BattleObject> allList = battleField.battleObjMgr.allBattleObjDict.Values.ToList<BattleObject>();
        // 修复:使用HashSet优化性能,避免重复设置
        var targetSet = new HashSet<BattleObject>(targetList);
        var highlightSet = new HashSet<BattleObject>(highlightList);
        caster.heroInfoBar.SetActive(false);
   //    //   做一个微微的提前
   //    MoveToTarget(mainTarget.Camp, mainTarget.teamHero.positionNum, entry.AnimationEnd - 0.05f, () => DoSkillLogic(_onComplete));
   // }
        foreach (BattleObject bo in allList)
        {
            bool isHighlight = highlightSet.Contains(bo);
            bool isTarget = targetSet.Contains(bo);
            if (isHighlight)
            {
                bo.layerMgr.SetFront();
            }
            else
            {
                bo.layerMgr.SetBack();
            }
   //   这里其实是技能后摇结束的地方
   protected virtual void DoSkillLogic(Action _onComplete = null)
   {
   }
            bo.heroInfoBar.SetActive(isTarget);
        }
   protected TrackEntry PlayCastAnimation(Action onComplete = null)
   {
      // 播放施法动作
      return caster.motionBase.PlaySkillAnimation(skillConfig, onComplete,
            OnStartSkillFrame,//攻击前摇结束
            OnActiveSkillFrame);//攻击中摇结束
   }
        battleField.battleRootNode.skillMaskNode.SetActive(true);
        battleField.battleRootNode.SetSortingOrder();
    }
   public void MoveToTarget(BattleCamp camp, BattleObject target, float duration = 0.2f, Action _onComplete = null)
   {
      targetNode = battleField.GetTeamNode(camp, target);
    // 命中目标回调:处理所有被命中的目标
    protected virtual void OnHitTargets(int _hitIndex, List<HB427_tagSCUseSkill.tagSCUseSkillHurt> hitList)
    {
        foreach (var hurt in hitList)
        {
            BattleObject target = caster.battleField.battleObjMgr.GetBattleObject((int)hurt.ObjID);
            if (target == null)
            {
                Debug.LogError("目标为空 target == null ObjId : " + hurt.ObjID);
                continue;
            }
      Vector2 offset = new Vector2(skillConfig.CastDistance, 0);
      RectTransform selfRect = caster.heroRectTrans;
      RectTransform targetRect = targetNode;
            OnHitEachTarget(_hitIndex, target, hurt);
        }
    }
      var tweener = BattleUtility.MoveToTarget(selfRect, targetRect, offset, duration, _onComplete);
      battleField.battleTweenMgr.OnPlayTween(tweener);
   }
    // 处理单个目标被命中:应用伤害和施法者效果
    protected virtual void OnHitEachTarget(int _hitIndex, BattleObject target, HB427_tagSCUseSkill.tagSCUseSkillHurt hurt)
    {
        List<int> damageDivide = new List<int>();
        if (_hitIndex == 0 && skillConfig.DamageDivide.Length <= 0)
        {
            damageDivide.Add(10000);
        }
        else
        {
            if (skillConfig.DamageDivide.Length <= _hitIndex)
            {
                Debug.LogError("技能伤害分布配置错误 skillId: " + skillConfig.SkillID + " hitIndex: " + _hitIndex);
                damageDivide.Add(10000);
            }
            else
            {
                damageDivide = skillConfig.DamageDivide[_hitIndex].ToList();
            }
        }
   public void MoveToTarget(BattleCamp camp, SkillConfig skillCfg, float duration = 0.2f, Action _onComplete = null)
   {
      targetNode = battleField.GetTeamNode(camp, skillCfg);
        // 伤害分布计算和应用
        long totalDamage = GeneralDefine.GetFactValue(hurt.HurtHP, hurt.HurtHPEx);
        List<long> damageList = BattleUtility.DivideDamageToList(damageDivide.ToArray(), totalDamage);
      Vector2 offset = new Vector2(skillConfig.CastDistance, 0);
      RectTransform selfRect = caster.heroRectTrans;
      RectTransform targetRect = targetNode;
        // 获取临时数据并应用伤害
        int objID = (int)target.ObjID;
        tempDropList.TryGetValue(objID, out BattleDrops battleDrops);
        tempDeadPackList.TryGetValue(objID, out HB422_tagMCTurnFightObjDead deadPack);
        target.Hurt(damageList, totalDamage, hurt, skillConfig, _hitIndex, battleDrops, deadPack);
      var tweener = BattleUtility.MoveToTarget(selfRect, targetRect, offset, duration, _onComplete);
      battleField.battleTweenMgr.OnPlayTween(tweener);
   }
        // 处理施法者相关效果
        caster.SuckHp(hurt.SuckHP, skillConfig);
        caster.HurtByReflect(hurt.BounceHP, skillConfig);
    }
    // 处理死亡相关逻辑:分配掉落和经验
    protected void HandleDead()
    {
        var deadPackList = BattleUtility.FindDeadPack(packList);
        if (deadPackList.Count <= 0) return;
        CheckAfterDeadhPack();
        // 修复:先收集要删除的包,避免在foreach中修改集合
        var dropPacksToRemove = new List<H0704_tagRolePackRefresh>(dropPackList);
        foreach (var _dropPack in dropPacksToRemove)
        {
            PackageRegedit.Distribute(_dropPack);
            packList.Remove(_dropPack);
        }
        // 获取并分配掉落物品和经验
        var dropPack = PackManager.Instance.GetSinglePack(PackType.DropItem);
        var itemDict = dropPack.GetAllItems();
        List<ItemModel> itemList = new List<ItemModel>(itemDict.Values.Where(item => item != null && item.isAuction));
        var dropAssign = AssignDrops(itemList, deadPackList.Count);
        var expAssign = AssignExp(expPackList, deadPackList.Count);
        // 构造BattleDrops并缓存
        for (int i = 0; i < deadPackList.Count; i++)
        {
            int objID = (int)deadPackList[i].ObjID;
            BattleObject deadTarget = battleField.battleObjMgr.GetBattleObject(objID);
            // 修复:添加空值检查
            if (deadTarget == null)
            {
                Debug.LogError($"找不到死亡目标,ObjID: {objID}");
                continue;
            }
            List<int> itemIndexList = dropAssign[i].Select(item => item.gridIndex).ToList();
            BattleDrops battleDrops = new BattleDrops()
            {
                rectTransform = deadTarget.heroRectTrans,
                dropItemPackIndex = itemIndexList,
                expDrops = expAssign[i]
            };
   public void TurnBack(Action _onComplete)
   {
      if (skillConfig.CastDistance < 0)
      {
         //   转身
         caster.heroGo.transform.localScale = new Vector3(-1, 1, 1);
      }
      _onComplete?.Invoke();
   }
            // 修复:避免字典键冲突,使用安全的添加方式
            if (!tempDropList.ContainsKey(objID))
            {
                tempDropList.Add(objID, battleDrops);
            }
            else
            {
                Debug.LogWarning($"tempDropList中已存在ObjID={objID}的记录,将覆盖原值");
                tempDropList[objID] = battleDrops; // 覆盖现有值
            }
   public void BackToOrigin(Action _onComplete = null)
   {
      RectTransform selfRect = caster.heroRectTrans;
      Vector2 targetAnchoredPos = Vector2.zero;
      var tween = selfRect.DOAnchorPos(targetAnchoredPos, 0.2f)
         .SetEase(Ease.Linear)
         .OnComplete(() =>
         {
            //   转成正确方向
            caster.heroGo.transform.localScale = Vector3.one;
            _onComplete?.Invoke();
         });
            if (!tempDeadPackList.ContainsKey(objID))
            {
                tempDeadPackList.Add(objID, deadPackList[i]);
            }
            else
            {
                Debug.LogWarning($"tempDeadPackList中已存在ObjID={objID}的记录,将覆盖原值");
                tempDeadPackList[objID] = deadPackList[i]; // 覆盖现有值
            }
        }
      battleField.battleTweenMgr.OnPlayTween(tween);
   }
        // 修复:避免在遍历时修改集合,先收集后删除
        var deadPacksToRemove = new List<GameNetPackBasic>(deadPackList.Cast<GameNetPackBasic>());
        foreach (var deadPack in deadPacksToRemove)
        {
            packList.Remove(deadPack);
        }
    }
   protected void HighLightAllTargets()
   {
      // 高亮所有目标
      HashSet<BattleObject> highlightList = new HashSet<BattleObject>(battleField.battleObjMgr.GetBattleObjList(tagUseSkillAttack));
      highlightList.Add(caster);
    // 分配掉落物品:将掉落物品平均分配给死亡对象
    protected List<List<ItemModel>> AssignDrops(List<ItemModel> itemList, int deadCount)
    {
        var dropAssign = new List<List<ItemModel>>();
        for (int i = 0; i < deadCount; i++)
            dropAssign.Add(new List<ItemModel>());
        for (int i = 0; i < itemList.Count; i++)
            dropAssign[i % deadCount].Add(itemList[i]);
        return dropAssign;
    }
      //   把这些BO全高亮 或者说把除了这些的都放在遮罩后面
      //   YYL TODO
   }
    // 分配经验值:将经验包平均分配给每个死亡对象
    protected List<List<HB405_tagMCAddExp>> AssignExp(List<HB405_tagMCAddExp> expList, int deadCount)
    {
        var expAssign = new List<List<HB405_tagMCAddExp>>();
        for (int i = 0; i < deadCount; i++)
            expAssign.Add(new List<HB405_tagMCAddExp>());
   //   命中目标后的回调 正常是以各技能的方式来处理的
   protected virtual void OnHitTargets(int _hitIndex, List<HB427_tagSCUseSkill.tagSCUseSkillHurt> hitList)
   {
      for (int i = 0; i < hitList.Count; i++)
      {
         HB427_tagSCUseSkill.tagSCUseSkillHurt hurt = hitList[i];
        // 修复:检查除零风险
        if (deadCount == 0)
        {
            Debug.LogWarning("AssignExp: deadCount为0,无法分配经验");
            return expAssign;
        }
         BattleObject target = caster.battleField.battleObjMgr.GetBattleObject((int)hurt.ObjID);
         if (target == null)
         {
            Debug.LogError("目标为空 target == null ObjId : " + hurt.ObjID);
            continue;
         }
        // 修复:先收集要删除的包,避免在foreach中修改packList
        var expPacksToRemove = new List<HB405_tagMCAddExp>();
         // 伤害分布 (万分比)
         int[] damageDivide = skillConfig.DamageDivide[_hitIndex];
        foreach (var expPack in expList)
        {
            long totalExp = GeneralDefine.GetFactValue(expPack.Exp, expPack.ExpPoint);
            long avgExp = totalExp / deadCount;
            long remain = totalExp % deadCount;
         long totalDamage = GeneralDefine.GetFactValue(hurt.HurtHP, hurt.HurtHPEx);
            for (int i = 0; i < deadCount; i++)
            {
                long assignExp = avgExp + (i < remain ? 1 : 0);
                var newPack = new HB405_tagMCAddExp
                {
                    Exp = (uint)(assignExp % 100000000),
                    ExpPoint = (uint)(assignExp / 100000000),
                    Source = expPack.Source
                };
                expAssign[i].Add(newPack);
            }
            expPacksToRemove.Add(expPack);
        }
        // 统一删除收集的包
        foreach (var pack in expPacksToRemove)
        {
            packList.Remove(pack);
        }
         // 保证所有分配项加起来等于totalDamage,避免因整除导致的误差
         List<long> damageList = DivideDamageToList(damageDivide, totalDamage);
        return expAssign;
    }
         OnHitEachTarget(target, totalDamage, damageList, ref hurt);
      }
   }
    // 检查死亡后的包处理:处理技能包、掉落包、经验包
    protected void CheckAfterDeadhPack()
    {
        List<int> removeIndexList = new List<int>();
        for (int i = 0; i < packList.Count; i++)
        {
            var pack = packList[i];
   /// <summary>
   /// 保证所有分配项加起来等于totalDamage,避免因整除导致的误差
   /// </summary>
   protected List<long> DivideDamageToList(int[] damageDivide, long totalDamage)
   {
      List<long> fixedDamageList = new List<long>();
      long assigned = 0;
      int count = damageDivide.Length;
            // 复活基本都靠技能包
            if (pack is CustomHB426CombinePack combinePack && combinePack.startTag.Tag.StartsWith("Skill_"))
                break;
            if (pack is H0704_tagRolePackRefresh h0704Pack && h0704Pack.PackType == (byte)PackType.DropItem && h0704Pack.IsBind == 1)
            {
                dropPackList.Add(h0704Pack);
                removeIndexList.Add(i);
            }
            if (pack is HB405_tagMCAddExp h405Pack && h405Pack.Source == 2)
            {
                expPackList.Add(h405Pack);
                removeIndexList.Add(i);
            }
        }
      for (int i = 0; i < count; i++)
      {
         long damage;
         if (i == count - 1)
         {
            // 最后一个分配项修正为剩余
            damage = totalDamage - assigned;
         }
         else
         {
            damage = (totalDamage * damageDivide[i] + 5000) / 10000; // 四舍五入
            assigned += damage;
         }
         fixedDamageList.Add(damage);
      }
      return fixedDamageList;
   }
        for (int i = removeIndexList.Count - 1; i >= 0; i--)
            packList.RemoveAt(removeIndexList[i]);
    }
   protected virtual void OnHitEachTarget(BattleObject target, long totalDamage, List<long> damageList, ref HB427_tagSCUseSkill.tagSCUseSkillHurt hurt)
   {
      target.Hurt(damageList, totalDamage, hurt.AttackTypes);
    // 检查技能是否完成:综合检查所有完成条件
    public virtual bool IsFinished()
    {
        if (!isPlay) return false;
      //   击中目标的时候,不管近战远程 都确认一下是否有爆炸特效 然后播放
      if (skillConfig.ExplosionEffectId > 0)
      {
         // 播放爆炸特效
         target.battleField.battleEffectMgr.PlayEffect(
            target.ObjID,
            skillConfig.ExplosionEffectId,
            target.heroGo.transform
         );
      }
        // 检查技能效果是否完成
        if (skillEffect != null)
        {
            if (!skillEffect.IsFinished()) return false;
            skillEffect = null;
            OnSkillFinished();
            return false;
        }
      //   受伤之后辨别死亡状态 死亡包其实前后帧会多次触发 应该要即时remove其他的包来保证不重复
      if (target.IsDead())
      {
         // SkillRecordAction里的drop事件前移到dead之后
         HB422_tagMCTurnFightObjDead deadPack = FindDeadPack(target);
         CheckAfterDeadhPack(target, deadPack);
         if (deadPack != null)
         {
            //   处理掉落包
            for (int i = 0; i < dropPackList.Count; i++)
            {
               PackageRegedit.Distribute(dropPackList[i]);
            }
        // 检查其他技能动作是否完成
        if (otherSkillActionList.Count > 0)
        {
            for (int i = otherSkillActionList.Count - 1; i >= 0; i--)
            {
                var action = otherSkillActionList[i];
                if (action.IsFinished())
                {
                    otherSkillActionList.RemoveAt(i);
                    OnSkillFinished();
                }
            }
            if (otherSkillActionList.Count > 0) return false;
        }
            dropPackList.Clear();
        // 检查最终完成状态
        if (isFinished && moveFinished)
        {
            if (packList.Count > 0)
            {
                OnSkillFinished();
                return false;
            }
            target.PushExpPackList(new List<HB405_tagMCAddExp>(expPackList));
            return true;
        }
            expPackList.Clear();
        return false;
    }
            // 处理死亡包
            PackageRegedit.Distribute(deadPack);
            packList.Remove(deadPack);
         }
         //   复活包暂时不管 可能是技能的包
         // HB423_tagMCTurnFightObjReborn rebornPack = FindRebornPack(target);
         // if (rebornPack != null)
         // {
         //    //   处理复活包
         //    PackageRegedit.Distribute(rebornPack);
         //    packList.Remove(rebornPack);
         // }
      }
   }
   protected HB423_tagMCTurnFightObjReborn FindRebornPack(BattleObject target)
   {
      HB423_tagMCTurnFightObjReborn rebornPack = null;
      for (int i = 0; i < packList.Count; i++)
      {
         var pack = packList[i];
         if (pack is HB423_tagMCTurnFightObjReborn)
         {
            rebornPack = pack as HB423_tagMCTurnFightObjReborn;
            if (rebornPack.ObjID == target.ObjID)
            {
               return rebornPack;
            }
         }
         else if (pack is CustomHB426CombinePack)
         {
            var combinePack = pack as CustomHB426CombinePack;
            if (combinePack.startTag.Tag.StartsWith("Skill_"))
            {
               break; // 找到技能包就不需要再处理了
            }
         }
      }
      return null;
   }
    // 强制结束技能:立即结束所有技能相关的处理
    public virtual void ForceFinished()
    {
        skillEffect?.ForceFinished();
        otherSkillActionList.ForEach(action => action.ForceFinish());
        otherSkillActionList.Clear();
   protected HB422_tagMCTurnFightObjDead FindDeadPack(BattleObject target)
   {
      HB422_tagMCTurnFightObjDead deadPack = null;
      for (int i = 0; i < packList.Count; i++)
      {
         var pack = packList[i];
         //   寻找死亡包 找到死亡包之后要找掉落包 不能超过技能包
         if (pack is HB422_tagMCTurnFightObjDead)
         {
            deadPack = pack as HB422_tagMCTurnFightObjDead;
            if (deadPack.ObjID == target.ObjID)
            {
               return deadPack;
            }
         }
         else if (pack is CustomHB426CombinePack)
         {
            //   找死亡包不要越过技能包
            var combinePack = pack as CustomHB426CombinePack;
            if (combinePack.startTag.Tag.StartsWith("Skill_"))
            {
               break;
            }
         }
      }
      return null;
   }
        isFinished = true;
        moveFinished = true;
        isPlay = true;
   protected void CheckAfterDeadhPack(BattleObject target, HB422_tagMCTurnFightObjDead deadPack)
   {
      if (null == deadPack)
      {
         return;
      }
      var deadPackIndex = packList.IndexOf(deadPack);
      if (deadPackIndex < 0)
      {
         return;
      }
      List<int> removeIndexList = new List<int>();
      for (int i = deadPackIndex + 1; i < packList.Count; i++)
      {
         var pack = packList[i];
        // 处理所有剩余包
        while (packList.Count > 0)
        {
            var pack = packList[0];
            packList.RemoveAt(0);
         //    复活基本都靠技能包
         if (pack is CustomHB426CombinePack)
         {
            var combinePack = pack as CustomHB426CombinePack;
            if (combinePack.startTag.Tag.StartsWith("Skill_"))
            {
               break; // 找到技能包就不需要再处理了
            }
         }
         else if (pack is H0704_tagRolePackRefresh)
         {
            var h0704Pack = pack as H0704_tagRolePackRefresh;
            if (h0704Pack.PackType == (byte)PackType.DropItem)
            {
               //   掉落的
               if (h0704Pack.IsBind == 1)
               {
                  //   掉落的物品
                  dropPackList.Add(h0704Pack);
                  removeIndexList.Add(i);
               }
               else if (h0704Pack.IsBind == 0)
               {
                  //   替换的
               }
            }
         }
         else if (pack is HB405_tagMCAddExp)
         {
            var h405Pack = pack as HB405_tagMCAddExp;
            if (pack is CustomHB426CombinePack combinePack && combinePack.startTag.Tag.StartsWith("Skill_"))
            {
                var otherSkillAction = combinePack.CreateSkillAction();
                otherSkillAction.fromSkillId = skillConfig.SkillID;
                otherSkillAction.ForceFinish();
            }
            else
            {
                if (pack is CustomB421ActionPack actionPack)
                    actionPack.Distribute();
                PackageRegedit.Distribute(pack);
            }
        }
    }
            //B4 05 获得经验 #tagMCAddExp 通知获得的经验,
            //可用于做经验获得表现 Source = 2 时为主线击杀怪物获得经验
            if (h405Pack.Source == 2)
            {
               expPackList.Add(h405Pack);
               removeIndexList.Add(i);
            }
         }
    // 技能完成处理:正常完成时的清理工作
    public void OnSkillFinished()
    {
        // 修复:使用循环代替递归,避免栈溢出风险
        try
        {
            while (true)
            {
                // 验证技能效果是否完成
                if (skillEffect != null && !skillEffect.IsFinished())
                    return;
                if (skillEffect != null)
                {
                    skillEffect = null;
                    continue; // 使用continue代替递归调用
                }
      }
                // 验证其他技能动作是否完成
                if (otherSkillActionList.Count > 0)
                {
                    bool hasFinishedAction = false;
                    for (int i = otherSkillActionList.Count - 1; i >= 0; i--)
                    {
                        var action = otherSkillActionList[i];
                        if (action.IsFinished())
                        {
                            otherSkillActionList.RemoveAt(i);
                            hasFinishedAction = true;
                        }
                    }
                    if (hasFinishedAction)
                    {
                        continue; // 使用continue代替递归调用
                    }
                    return;
                }
      for (int i = removeIndexList.Count - 1; i >= 0; i--)
      {
         packList.RemoveAt(removeIndexList[i]);
      }
   }
   public virtual bool IsFinished()
   {
      return isFinished;
   }
                break; // 没有更多需要处理的,退出循环
            }
   public virtual void ForceFinished()
   {
      isFinished = true;
   }
            // 处理剩余包
            while (packList.Count > 0)
            {
                var pack = packList[0];
                packList.RemoveAt(0);
   public void OnSkillFinished()
   {
      while (packList.Count > 0)
      {
         var pack = packList[0];
         packList.RemoveAt(0);
                if (pack is CustomHB426CombinePack combinePack && combinePack.startTag.Tag.StartsWith("Skill_"))
                {
                    BattleDebug.LogError("other skill casting " + combinePack.startTag.Tag);
                    var otherSkillAction = combinePack.CreateSkillAction();
                    otherSkillAction.fromSkillId = skillConfig.SkillID;
                    otherSkillActionList.Add(otherSkillAction);
                    return;
                }
         if (pack is CustomHB426CombinePack)
         {
            var combinePack = pack as CustomHB426CombinePack;
            if (combinePack.startTag.Tag.StartsWith("Skill_"))
            {
               otherSkillAction = combinePack.CreateSkillAction();
               return;
            }
         }
                if (pack is CustomB421ActionPack actionPack)
                    actionPack.Distribute();
                PackageRegedit.Distribute(pack);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"OnSkillFinished异常: {ex.Message},技能ID={skillConfig.SkillID}");
            // 确保状态一致性,即使出现异常也要标记完成
            isFinished = true;
            throw; // 重新抛出异常供上层处理
        }
         PackageRegedit.Distribute(pack);
      }
        isFinished = true;
    }
      isFinished = true;
   }
    // 添加清理方法:防止内存泄漏
    public virtual void Cleanup()
    {
        tempDropList?.Clear();
        tempDeadPackList?.Clear();
        otherSkillActionList?.Clear();
        dropPackList?.Clear();
        expPackList?.Clear();
        skillEffect = null;
        packList = null;
    }
}