ThreeKingdomsSlingshot/Assets/Scripts/Runtime/ActionResolver.cs

1708 lines
106 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace TKS
{
/// <summary>슬링샷 한 번의 결과 요약.</summary>
public class ActionOutcome
{
public bool BonusMove; // 보병: 최종 목표점 명중 → 추가 이동
public bool Returned; // 기병: 최종 목표점 명중 → 제자리 복귀
public bool Overwatch; // 창병: 최종 목표점 명중 → 대기(견제)
public bool Crit; // 궁병·책사: 첫 피격 = 타겟 + 최종 목표점 명중 → 크리티컬
public bool MovedOnly; // 행동 유닛 자신은 공격하지 않음(이동 · 밀어내기만)
public bool Fired; // 궁병·책사: 투사체를 쐈다(타겟이 없으면 목표점 이동만 · 쏘지 않음)
public Unit ShotHit; // 궁병·책사: 투사체가 처음 맞힌 유닛(아군 포함 · 책사 광역 중심) · null = 안 쏨·빗나감
public int DamageDealt;
public int CounterTaken;
public List<Unit> Attacked = new List<Unit>();
/// <summary>궁병·책사 사격에 맞은 같은 편(오사 · 책사 광역 포함 · PD 2026-11-05 #1087 ⑤⑥).</summary>
public List<Unit> FriendlyHit = new List<Unit>();
public int FriendlyDamage;
/// <summary>충돌로 밀려난 유닛(아군·적군 · PD 2026-11-04 #1080).</summary>
public List<Unit> Pushed = new List<Unit>();
/// <summary>밀린 아군이 적과 닿아 얻은 공격 등 부가 설명(HUD 문구).</summary>
public List<string> Notes = new List<string>();
/// <summary>실제로 지나간 경로(시작 포함). 창병 견제 판정용.</summary>
public List<Vector2> Path = new List<Vector2>();
// ---------- 스킬(PD #1093 B) ----------
/// <summary>이 행동에 걸린 예약 액티브(next_action) · null = 없음.</summary>
public SkillDef SkillUsed;
/// <summary>추가 이동 횟수(기본 1 · 인덕 extra_move_count) · 추가 이동에서 공격 가능(extra_move_attack).</summary>
public int BonusMoves = 1;
public bool BonusAttack;
/// <summary>이 행동으로 밀리거나 넉백된 유닛의 이동 구간(청룡언월 「견제 무제한」 판정 · 기믹 지대 스윕).</summary>
public List<Displacement> Displaced = new List<Displacement>();
/// <summary>보병 연쇄 교환 수(튕겨나는 도중 다른 적과 부딪힘 · PD 2026-11-06 #1098).</summary>
public int Chains;
}
public struct Displacement
{
public Unit Unit;
public Vector2 From;
public Vector2 To;
}
/// <summary>
/// 슬링샷 벡터(시작점 → 목표점)를 병종 규칙대로 이동·공격으로 해석한다 (PD 2026-11-04 #1080 충돌 규칙).
/// ① 보병: 경로 위 첫 유닛(아군·적군)에 부딪히면 알까기처럼 그 유닛을 남은 힘만큼 밀어내고 자신은 반대로 튕김 · 적이면 공격(반격 받음) · 목표점 명중 시 추가 이동 1회 ·
/// 적과 싸운 뒤 튕겨나는 도중 다른 적과 부딪히면 그 적과도 피해·반격 교환 + 다시 튕김(연쇄 1회 · 아군이면 밀기만 · PD 2026-11-06 #1098)
/// ② 기병 = 적을 관통해 이동: 유닛을 무시하고 관통 · 경로 위 적은 모두 피해(옆으로 밀림) · 아군은 지나칠 거리가 안 나오면 그 아군 직전에 멈춤 ·
/// 제자리 복귀 없음(PD 2026-11-10 「유저가 인지하기 어려움 → 제거 · 기병 특징 = 적을 관통해 이동」)
/// ③ 창병 = 적을 크게 밀치고 자신은 적게 밀림: 첫 유닛에 부딪히면 그 유닛을 남은 거리 × spearPushRatio 만큼 밀치고 자신은 그 × spearRecoilRatio 만큼 반대로 밀림 ·
/// 적이면 피해(반격 받음) · 아군이면 밀기만 · 대기(견제) 없음(PD 2026-11-10 「유저가 인지하기 어려움 → 제거」)
/// ④ 궁병: 사거리 = 이동 범위 × (1+비율) · 조준 방향 사거리 안의 적은 제자리에서 사격 · 이동과 사격을 함께 하지 않는다(PD 2026-11-16 · 그 전 = 사거리 밖 +비율 안이면 다가가 사격) ·
/// 더 멀면 목표점까지 이동(쏘지 않음) · 사격 = 타겟 방향 화살 투사체 → 경로 위 첫 유닛(아군 포함)이 맞음 · 관통 없음 · 반격 없음 ·
/// 첫 피격 = 타겟 + 목표점 명중 시 크리티컬(PD 2026-11-05 #1087 ⑥) · 근접 전투는 피해 50 % · 피격 +50 %(Combat.Damage)
/// ④' 책사: 궁병과 같은 사격 + 맞은 유닛 주변 반경 안 다른 유닛 전원(아군 포함)에게 광역 피해(PD 2026-11-05 #1087 ⑤)
/// ⑤ 밀린 아군(행동 유닛과 같은 진영)이 상대 유닛과 닿으면 그 자리에서 공격 1회(조작마다 · 자기 행동은 소모하지 않음)
/// 스킬(PD #1093 B): 수치는 SkillMods 질의(밀기·튕김·관통·사거리·사선·광역·피해) · 예약 액티브는 Resolve 앞뒤에서 장착·소모(SkillSystem).
/// 지형 기믹(PD #1097): 충돌·투사체·미끄러짐·지대 = Gimmicks/ActionResolver.Gimmicks.cs · 가상 실행(적 AI) = Sim.Active 동안 연출 없이 즉시.
/// </summary>
public partial class ActionResolver
{
readonly BalanceConfig cfg;
readonly BattleManager battle;
readonly System.Random rng;
/// <summary>연속 공격(repeat_action)의 첫 타격에서 대상이 밀릴 수 있는 한도(월드 거리 = 밀림 + 자신이 물러나는 거리 · 0 = 한도 없음) — Resolve 가 첫 돌진 동안만 넣는다.</summary>
float repeatPushCap;
/// <summary>지금 행동 중인 유닛(Resolve) — 연쇄로 밀린 같은 편이 상대와 부딪히면 피해를 주는 판정(Push)에 쓴다.</summary>
Unit acting;
public ActionResolver(BalanceConfig cfg, BattleManager battle, System.Random rng)
{
this.cfg = cfg;
this.battle = battle;
this.rng = rng;
}
public IEnumerator Resolve(Unit u, Vector2 target, bool moveOnly, ActionOutcome o)
{
Vector2 origin = u.Position;
float slingDist = Vector2.Distance(origin, target);
Vector2 aimed = target;
target = ReachPoint(u, target); // 늪·고지 이동 비용 = 실제 도달점(근접 병종 · PD #1097) · 조인 철벽 = 반경 안 이동 비용 +
Vector2 delta = target - origin;
float dist = delta.magnitude;
o.Path.Add(origin);
pushImpacted.Clear();
if (dist < 0.001f || !u.IsAlive) yield break;
Vector2 dir = delta / dist;
var prevActing = acting; // 스킬이 다른 유닛을 행동시키는 경우(중첩) 끝나면 되돌린다
acting = u;
GimmickBegin(o);
var skills = SkillSystem.Current;
if (skills != null)
{
skills.BeginAction(u, moveOnly, o, dir, slingDist); // 예약 액티브 장착 + 발동 연출 · 돌진 거리 비율(만인지적·강동의 호걸·적토마)
if (skills.Ctx != null && CrossesSlowTerrain(u, origin, aimed)) skills.Ctx.HitTerrain = true; // 이동 감소 지형(늪·고지)을 지남(맹획 남만왕 · 조인 철벽 감속은 제외 · Fable 검토 C6)
}
// 슬링샷 돌진 중 = 병종 돌진 포즈 1프레임 고정 · 끝나면 대기 (PD 2026-11-05 #1084)
if (u.View != null) u.View.SetCharging(true);
// 정보 연환격(repeat_action) = 같은 거리·방향으로 한 번 더(멈춘 자리에서)
int runs = !moveOnly && SkillMods.Has(u, SkillKeys.RepeatAction) ? 2 : 1;
// 첫 타격 밀림 한도(PD 2026-11-13 정보 「첫 타격 시 밀려나는 거리는 다음 연속 공격 가능한 거리만큼만 · 다음 연속 공격이 동일한 힘으로 공격 가능하도록 공격 가능한 범위까지만」):
// 다음 돌진 거리(같은 거리 = 지금 당긴 거리) × 효과 표 repeat_action p2(빈칸 1) 안에서만 밀림 — 밀림 + 자신이 물러나는 거리가 그보다 길면 두 번째 돌진이 닿지 않는다
var rep = runs > 1 ? SkillMods.First(u, SkillKeys.RepeatAction) : null;
float repReach = rep != null ? delta.magnitude * Mathf.Max(0f, rep.Get(1, 1f)) : 0f;
for (int k = 0; k < runs && u.IsAlive; k++)
{
if (k > 0 && skills != null) skills.VfxAllowRehitAll(); // 정보 연환격: 두 번째 돌진에 맞은 적도 피격 이펙트(PD 2026-11-20 42차 「첫번째 피격 이펙트가 두번째에 발생하지 않는 현상」)
repeatPushCap = runs > 1 && k == 0 ? repReach : 0f;
if (k > 0)
{
yield return Fx.Wait(0.15f);
origin = u.Position;
target = battle.Board.ClampInside(origin + delta, u.Radius);
Vector2 d2 = target - origin;
dist = d2.magnitude;
if (dist < 0.05f) break;
dir = d2 / dist;
DashBegin(u, dir);
o.Notes.Add("한 번 더");
}
yield return RoutineFor(u, origin, dir, dist, target, moveOnly, o);
}
if (!moveOnly && u.IsAlive && skills != null && SkillMods.First(u, SkillKeys.EndBlast, true) != null) EndBlast(u, skills, SkillMods.First(u, SkillKeys.EndBlast, true), o); // 이각 약탈(PD 2026-11-20)
repeatPushCap = 0f;
yield return GimmickAfter(u, moveOnly, o, !(UnitTypeInfo.IsRanged(u.Type) && o.Fired)); // 빙판 · 지대 스윕 · 강(PD #1097)
if (u.View != null) u.View.SetCharging(false);
// 호위(관평·강유)가 대상 앞으로 달려갔다 제자리로 돌아온 뒤 행동 끝(다음 행동·적 AI 가 옮겨 둔 판정 위치를 보지 않게 · 2026-11-12 PD 호위 이동) ·
// 가상 실행(Sim.Run = 한 프레임 안에서 끝까지)에서는 기다리지 않음(기다리면 멈춤)
if (skills != null)
while (!Sim.Active && skills.GuardRunning) yield return null;
if (skills != null) yield return skills.EndAction(u, o); // 출혈·중독 · 지대 · 재행동 · 예약 소모 · 쿨
if (skills != null)
while (!Sim.Active && skills.GuardRunning) yield return null;
acting = prevActing;
}
/// <summary>병종 루틴 선택 — 장착 스킬이 바꾸는 것: 동탁 폭정(난동) · 손견·안량 관통(보·창도 기병처럼) · 축융 비도(창병이 궁병처럼 사격).</summary>
IEnumerator RoutineFor(Unit u, Vector2 origin, Vector2 dir, float dist, Vector2 target, bool moveOnly, ActionOutcome o)
{
if (!moveOnly && SkillMods.Has(u, SkillKeys.Rampage))
{
yield return RampageRoutine(u, origin, dir, o);
yield break;
}
if (!moveOnly && SkillMods.Has(u, SkillKeys.PushThrough)) // 맹획 남만왕(PD 2026-11-20 「동탁과 마찬가지로 적과 부딪혀도 최대 이동거리만큼 전진 · 적만 튕겨지고 맹획은 튕겨지지 않도록」)
{
yield return RampageRoutine(u, origin, dir, o, dist);
yield break;
}
if (!moveOnly && (SkillMods.Has(u, SkillKeys.ShotAsArcher) || HasSpecialShot(u))) // 축융 비도 · 주태 검기(보병의 특수 사격 · Fable 검토 A1)
{
yield return ArcherRoutine(u, origin, dir, dist, target, moveOnly, o);
yield break;
}
if (!moveOnly && !UnitTypeInfo.IsRanged(u.Type) && u.Type != UnitType.Cavalry && SkillMods.Has(u, SkillKeys.PierceThrough))
{
yield return CavalryRoutine(u, origin, dir, dist, target, moveOnly, o);
yield break;
}
switch (u.Type)
{
case UnitType.Infantry:
yield return InfantryRoutine(u, origin, dir, dist, target, moveOnly, o);
break;
case UnitType.Spear:
yield return SpearRoutine(u, origin, dir, dist, target, moveOnly, o);
break;
case UnitType.Cavalry:
yield return CavalryRoutine(u, origin, dir, dist, target, moveOnly, o);
break;
case UnitType.Archer:
case UnitType.Strategist:
yield return ArcherRoutine(u, origin, dir, dist, target, moveOnly, o);
break;
}
}
// ---------- 미리보기(드라이런) ----------
/// <summary>조작 중 표시용: 이 슬링샷으로 행동 유닛이 직접 공격하게 될 적 목록(밀린 아군의 공격은 예측하지 않음).</summary>
public List<Unit> PredictTargets(Unit u, Vector2 target, bool moveOnly)
{
var result = new List<Unit>();
if (moveOnly) return result;
Vector2 origin = u.Position;
target = ReachPoint(u, target);
Vector2 delta = target - origin;
float dist = delta.magnitude;
if (dist < 0.001f) return result;
Vector2 dir = delta / dist;
float hitDist;
var skills = SkillSystem.Current;
bool prev = skills != null && skills.PreviewBegin(u);
GimmickLayer.PreviewMode = true; // 아군 조준 = 숨은 함정을 모른다(PD #1097)
try
{
switch (u.Type)
{
case UnitType.Infantry:
case UnitType.Spear:
{
if (SkillMods.Has(u, SkillKeys.PierceThrough) || SkillMods.Has(u, SkillKeys.Rampage) || SkillMods.Has(u, SkillKeys.PushThrough)) goto case UnitType.Cavalry; // 맹획 남만왕 = 경로 위 전원(PD 2026-11-20)
var first = SkillMods.Has(u, SkillKeys.PassAllies) ? FirstEnemyBeforeWall(u, origin, dir, dist, out hitDist) : FirstUnitBeforeWall(u, origin, dir, dist, out hitDist);
if (first != null && first.Faction != u.Faction) result.Add(first);
break;
}
case UnitType.Cavalry:
{
float travel = Combat.FreeTravel(u, origin, dir, PassLossTravel(u, origin, dir, dist, Combat.FreeTravel(u, origin, dir, dist, false, false)), false, false); // 실제 행동(CavalryRoutine)과 같은 관통 감쇠
if (!PierceAllies(u)) travel = StopBeforeUnclearedAllies(u, origin, dir, travel);
var dists = new List<float>();
result.AddRange(Combat.EnemiesOnPath(u, origin, dir, travel, dists));
break;
}
case UnitType.Archer:
case UnitType.Strategist:
{
var p = PlanShot(u, origin, dir, target);
if (!p.Fires) break;
if (p.Hit != null && p.Hit.Faction != u.Faction) result.Add(p.Hit);
foreach (var s in p.Splash)
{
if (s.Faction != u.Faction) result.Add(s);
}
break;
}
}
}
finally
{
GimmickLayer.PreviewMode = false;
if (skills != null) skills.PreviewEnd(u, prev);
}
return result;
}
/// <summary>조작 중 표시용: 궁병·책사의 사격 계획(화살 경로선 · 첫 피격 유닛 · 책사 광역). 원거리 병종이 아니거나 이동만이면 null.</summary>
public ShotPlan PreviewShot(Unit u, Vector2 target, bool moveOnly)
{
if (moveOnly || u == null || !UnitTypeInfo.IsRanged(u.Type)) return null;
Vector2 delta = target - u.Position;
float dist = delta.magnitude;
if (dist < 0.001f) return null;
var skills = SkillSystem.Current;
bool prev = skills != null && skills.PreviewBegin(u);
GimmickLayer.PreviewMode = true;
try
{
var giant = SkillMods.First(u, SkillKeys.ShotGiant); // 예약한 거대 화살(황충) = 사거리와 무관한 실제 궤적으로
if (giant != null) return PlanGiant(u, delta / dist, giant);
var blast = SkillMods.First(u, SkillKeys.ShotBlast); // 예약한 폭발 사격(서서 화염구 등) = 실제와 같은 궤적 · 적이 없으면 사거리 끝 폭발
// 실제 순서(SpecialShot) = 관통 → 레이저 → 폭발
if (SkillMods.First(u, SkillKeys.ShotLaser) != null && !SkillMods.Has(u, SkillKeys.ShotPierce)) return PlanLaser(u, delta / dist); // 예약한 레이저(태사자) = 전장 끝까지 · 경로 위 적 전원
if (blast != null && !SkillMods.Has(u, SkillKeys.ShotPierce)) return PlanBlast(u, delta / dist, target, blast);
return PlanShot(u, u.Position, delta / dist, target);
}
finally
{
GimmickLayer.PreviewMode = false;
if (skills != null) skills.PreviewEnd(u, prev);
}
}
// ---------- 공통 질의 ----------
/// <summary>경로 위 첫 유닛. 벽이 그보다 먼저 있으면 null.</summary>
Unit FirstUnitBeforeWall(Unit u, Vector2 origin, Vector2 dir, float dist, out float hitDist)
{
Unit first = Combat.FirstUnitOnPath(u, origin, dir, dist, out hitDist);
if (first == null) return null;
float wall = Combat.FreeTravel(u, origin, dir, dist, false, false);
if (hitDist > wall + Combat.Epsilon)
{
hitDist = 0f;
return null;
}
return first;
}
/// <summary>조조 난세의 간웅(pass_allies): 아군은 통과 · 경로 위 첫 적(벽이 먼저면 null).</summary>
Unit FirstEnemyBeforeWall(Unit u, Vector2 origin, Vector2 dir, float dist, out float hitDist)
{
Unit first = Combat.FirstEnemyOnPath(u, origin, dir, dist, out hitDist);
if (first == null) return null;
float wall = Combat.FreeTravel(u, origin, dir, dist, false, false);
if (hitDist > wall + Combat.Epsilon)
{
hitDist = 0f;
return null;
}
return first;
}
/// <summary>관통이 아군도 지나는가(손견 강동의 호랑이 · 손책 소패왕 = pierce_through p1 1).</summary>
static bool PierceAllies(Unit u)
{
foreach (var h in SkillMods.Get(u, SkillKeys.PierceThrough))
if (h.E.P >= 0.5f) return true;
return false;
}
/// <summary>아군 통과 이동(유닛 무시 · 벽·장애물만) → 끝이 유닛과 겹치면 겹치지 않는 곳까지 되짚음.</summary>
IEnumerator MoveThrough(Unit u, Vector2 origin, Vector2 dir, float dist, ActionOutcome o)
{
float free = Combat.FreeTravel(u, origin, dir, dist, true, false);
Vector2 end = BackOffFromUnits(u, origin, dir, free, true);
yield return Move(u, end, o);
o.MovedOnly = true;
}
// ---------- 보병: 알까기 충돌 ----------
IEnumerator InfantryRoutine(Unit u, Vector2 origin, Vector2 dir, float dist, Vector2 target, bool moveOnly, ActionOutcome o)
{
if (moveOnly)
{
yield return MoveFree(u, origin, dir, dist, o);
yield break;
}
float hitDist;
bool passAllies = SkillMods.Has(u, SkillKeys.PassAllies); // 조조 난세의 간웅 = 아군 통과
Unit first = passAllies ? FirstEnemyBeforeWall(u, origin, dir, dist, out hitDist) : FirstUnitBeforeWall(u, origin, dir, dist, out hitDist);
float gDist;
Vector2 gNormal;
var gim = BlockAhead(u, origin, dir, dist, first != null ? hitDist : dist, out gDist, out gNormal);
if (gim != null)
{
yield return HitGimmick(u, gim, origin, dir, dist, gDist, gNormal, o); // 장애물 기믹이 먼저(PD #1097)
yield break;
}
if (first == null)
{
if (passAllies) yield return MoveThrough(u, origin, dir, dist, o);
else yield return MoveFree(u, origin, dir, dist, o);
yield break;
}
Vector2 contact = origin + dir * hitDist;
PreHit(u, first, contact, dist); // 닿기 직전 이펙트(표 prehit · 주창 대도 일섬 베기 · PD 2026-11-12)
yield return MoveStraight(u, contact, o, dist); // 쏜 힘으로 날아가 속도를 가진 채 부딪히고 바로 반응(PD #1081 · 2026-11-16 물리)
DashEnd(u); // 슬링샷 직진 끝 = 돌진 이펙트 소멸(튕김은 반응 · PD 2026-11-10)
float remaining = Mathf.Max(0f, dist - hitDist); // 남은 이동 거리(고순 재행동 한도)
float power = ImpactPower(dist, hitDist); // 부딪히는 힘(밀어내기·자기 튕김)
bool enemy = first.Faction != u.Faction;
int impact = 0;
if (enemy)
{
impact = ImpactExchange(u, first, o); // 부딪힌 순간 피해·반격을 즉시 주고받는다(연출 대기 없음)
if (!u.IsAlive) yield break;
}
else
{
o.MovedOnly = true;
}
Vector2 n = first.Position - contact;
n = n.sqrMagnitude > 1e-6f ? n.normalized : dir;
if (SkillMods.Has(u, SkillKeys.SwapOnHit) && first.IsAlive)
{
yield return SwapWith(u, first, origin, o); // 위연 자오곡 기책: 명중 대상 ↔ 출발 위치(튕김 없음)
}
else if (enemy && first.IsAlive && SkillMods.Has(u, SkillKeys.AimPush))
{
// 조조 난세의 간웅: 자신은 밀리지 않고 붙잡은 적을 다시 슬링샷 조작으로 날림(2026-11-19 PD 「적을 붙잡게 되면 다시 슬링샷 조작이 가능하도록 ·
// 슬링샷 방향으로 대상이 된 유닛을 날려야」 · 그 전 = 탭한 방향) — 붙잡힌 적에서 끈 방향 = 날릴 방향 · 끈 세기(조준 거리 = 일반 슬링과 같은 환산 · 조조 슬링 최대까지) = 부딪힌 힘 대신 ·
// 적·자동·가상 실행 = 예전대로 슬링 방향 · 부딪힌 힘
Vector2 aimDir = n;
float slingDist = -1f;
var sk = SkillSystem.Current;
bool manual = sk != null && SkillSystem.ManualTap(u);
if (sk != null)
yield return sk.WaitTap(u, SkillSystem.TapKind.Sling, first.Position, 0f,
(o.SkillUsed != null ? o.SkillUsed.NameKo + " — " : "") + "붙잡은 적을 끌어 날릴 방향·세기를 정하세요", first.Position + n,
w => { var d = w - first.Position; if (d.sqrMagnitude > 1e-4f) { aimDir = d.normalized; if (manual) slingDist = d.magnitude; } }, first);
// 2026-11-20 PD 「조조의 이동거리만큼 동일하게 날릴 수 있어야 · 반대 방향으로 날리려고 할 경우 금방 멈춰버림 → 슬링샷 이동 거리만큼」 =
// 손 조작 = 끈 거리 그대로 날아감(예전 = 끈 거리 × collisionPushRatio 0.21 · 끝까지 당겨도 약 1.5) · 조조 자신은 막지 않음(Push 의 pusher) · 적·자동 = 예전 계산
float force = slingDist > 0f ? slingDist
: Mathf.Max(power, cfg.minDragDistance) * cfg.collisionPushRatio * SkillMods.PushMult(u, true) * PushTakenMult(first);
if (first.IsAlive) yield return Push(first, aimDir, force, u, o);
}
else
{
// 알까기: 부딪힌 순간 양쪽이 동시에 튕긴다 — 상대 = 접촉 방향 × 부딪히는 힘 × collisionPushRatio · 자신 = 반대 방향 × 부딪히는 힘 × collisionSelfBounceRatio
yield return Bounce(u, first, n, power, o, enemy ? impact : 0, Mathf.Max(0, cfg.bounceChainMax), dir); // 처음 닿은 유닛이 아군이어도 같은 연쇄(PD 2026-11-17 「아군을 친 경우에도 연쇄로 튕겨져 공격하거나 아군을 더 미는」 · 그 전 = 아군을 먼저 치면 연쇄 없음) · 부딪힌 뒤 튕김 = 힘이 남는 동안 연쇄(bounceChainMax 한도 · PD 2026-11-16 · 그 전 = 1회 #1098) · 들어온 방향 = 슬링 방향(거울 반사)
}
if (!enemy && first.IsAlive) yield return PushedAllyAttack(first, o, u);
if (!enemy) PushContinue(u, remaining); // 고순: 아군을 밀친 뒤 남은 이동력으로 재행동
// 목표점 명중 추가 이동 = 제거(PD 2026-11-10 #1112 결정 ⑱ · 보병 특징 = 알까기·연쇄 · 재행동은 스킬로만)
}
/// <summary>고순 함진 돌파(push_continue): 아군·지형 오브젝트를 밀친 뒤 남은 이동 거리만큼 재행동 1회(슬링 상한 = 남은 거리).</summary>
void PushContinue(Unit u, float remaining)
{
var sk = SkillSystem.Current;
var s = sk != null ? sk.Of(u) : null;
if (s == null || !u.IsAlive || remaining < cfg.minDragDistance || !SkillMods.Has(u, SkillKeys.PushContinue, true)) return;
s.ReactCredits++;
s.ReactLimit = remaining;
}
/// <summary>위연: 명중 대상은 행동 유닛의 출발 위치로 · 행동 유닛은 대상 자리로(동시에).</summary>
IEnumerator SwapWith(Unit u, Unit t, Vector2 origin, ActionOutcome o)
{
Vector2 tFrom = t.Position;
Vector2 tTo = battle.Board.ClampInside(origin, t.Radius);
Vector2 uTo = battle.Board.ClampInside(tFrom, u.Radius);
bool done = false;
Fx.Run(Track(Fx.MoveAlong(t.transform, tFrom, tTo, cfg.moveSpeed * 1.5f, null), () => done = true));
Face(u, uTo - u.Position);
yield return Fx.MoveAlong(u.transform, u.Position, uTo, cfg.moveSpeed * 1.5f, null);
while (!done) yield return null;
t.Position = tTo;
u.Position = uTo;
o.Path.Add(uTo);
o.Displaced.Add(new Displacement { Unit = t, From = tFrom, To = tTo });
o.Notes.Add(t.DisplayName + " 자리 교환");
battle.NotifyChanged();
}
// ---------- 창병: 밀치기 + 반작용(PD 2026-11-06 #1098 · 밀며 함께 전진 폐기) ----------
IEnumerator SpearRoutine(Unit u, Vector2 origin, Vector2 dir, float dist, Vector2 target, bool moveOnly, ActionOutcome o)
{
if (moveOnly)
{
yield return MoveFree(u, origin, dir, dist, o);
yield break;
}
float hitDist;
Unit first = FirstUnitBeforeWall(u, origin, dir, dist, out hitDist);
float gDist;
Vector2 gNormal;
var gim = BlockAhead(u, origin, dir, dist, first != null ? hitDist : dist, out gDist, out gNormal);
if (gim != null)
{
yield return HitGimmick(u, gim, origin, dir, dist, gDist, gNormal, o); // 장애물 기믹이 먼저(PD #1097)
yield break;
}
if (first == null)
{
yield return MoveFree(u, origin, dir, dist, o);
yield break;
}
Vector2 contact = origin + dir * hitDist;
PreGuard(u, first, contact, Fx.ApproachDuration(Vector2.Distance(u.Position, contact), dist, cfg.moveSpeed));
yield return MoveStraight(u, contact, o, dist); // 쏜 힘으로 날아가 속도를 가진 채 부딪히고 즉시 밀기 시작(PD #1081 · 2026-11-16 물리)
DashEnd(u); // 슬링샷 직진 끝 = 돌진 이펙트 소멸(밀기·반작용은 반응 · PD 2026-11-10)
float remaining = ImpactPower(dist, hitDist); // 부딪히는 힘(PD 2026-11-16 · 그 전 = 남은 거리 dist − hitDist)
bool enemy = first.Faction != u.Faction;
if (enemy)
{
ImpactExchange(u, first, o); // 부딪힌 순간 피해·반격 즉시
if (!u.IsAlive) yield break;
}
else
{
o.MovedOnly = true;
}
// 밀치기 거리 = 부딪히는 힘 × spearPushRatio(보병보다 크게 · PD 2026-11-10) × 철척사모(push_mult) × 대상 거구(knockback_taken_pct)
float push = remaining * cfg.spearPushRatio * SkillMods.PushMult(u, true) * PushTakenMult(first);
// 창병이 밀려나는 거리 = 보병이 튕기는 거리(부딪히는 힘 × collisionSelfBounceRatio) × spearRecoilRatio(PD 2026-11-16 「창병은 보병보다 더 많이 밀고, 절반만 밀려야」) ·
// 상대를 쓰러뜨렸거나 상대가 밀리지 않아도 밀려난다(그 전 = 상대가 살아서 밀릴 때만 → 처치하는 타격에서는 전혀 튕기지 않았다) · 서황 대부 = 반작용도 ×(Fable 검토 C5)
float recoilFull = remaining * cfg.collisionSelfBounceRatio * UnitHitKeep() * cfg.spearRecoilRatio * (enemy ? SkillMods.AxeBounce(first) : 1f); // UnitHitKeep = 상대를 밀어내며 잃는 힘(PD 2026-11-16)
if (repeatPushCap > 0f && enemy && push + recoilFull > repeatPushCap) // 연환격 첫 타격: 밀림 + 창병이 물러나는 거리 ≤ 한도 → 같은 힘의 다음 돌진이 닿음
{
float s = repeatPushCap / (push + recoilFull);
push *= s;
recoilFull *= s;
}
bool pushed = first.IsAlive && push > 0.01f;
bool pushedDone = !pushed;
if (pushed) Fx.Run(Track(Push(first, dir, push, u, o), () => pushedDone = true));
float recoil = Reach(u, u.Position, -dir, recoilFull);
if (recoil > 0.01f && u.IsAlive) yield return SpearRecoil(u, -dir, recoil, first, Mathf.Max(0, cfg.bounceChainMax), o); // 물러나는 길에서 적과 닿으면 타격(PD 2026-11-19)
while (!pushedDone) yield return null;
battle.NotifyChanged();
if (pushed && !enemy) yield return PushedAllyAttack(first, o, u);
// 목표점 명중 → 대기(견제) = 제거(PD 2026-11-10) · 새 스킬 기획(2026-11-10 #1112)에도 견제 없음
}
/// <summary>
/// 창병 반작용(밀려남 · rd 방향 recoil 만큼): 벽·장애물·같은 편에 닿으면 정지 · 보는 방향은 유지(밀친 쪽을 본 채 물러남) ·
/// 물러나는 길에서 상대 유닛과 닿으면 타격(PD 2026-11-19 「창병도 튕겨날 때 적과 닿으면 타격」 · 그 전 = 닿으면 정지 · 피해 없음):
/// 닿은 순간 피해·반격 교환 → 그 상대를 창병처럼 밀치고(부딪히는 힘 × spearPushRatio) 다시 반작용(× collisionSelfBounceRatio × spearRecoilRatio) ·
/// 연쇄 한도 = bounceChainMax(다 쓰면 닿은 자리에서 정지). except = 방금 밀친 유닛(맞닿아 있어 경로 맨 앞에 잡힘 → 뺀다).
/// </summary>
IEnumerator SpearRecoil(Unit u, Vector2 rd, float recoil, Unit except, int chain, ActionOutcome o)
{
float h;
Unit foe = Combat.FirstUnitOnPathExcept(u, u.Position, rd, recoil, except, out h);
bool hit = foe != null && foe.Faction != u.Faction && !foe.Npc && h <= Combat.FreeTravel(u, u.Position, rd, recoil, false, false) + Combat.Epsilon;
if (!hit)
{
float back = Combat.FreeTravel(u, u.Position, rd, recoil, true, true, except);
NoteForced(u, u.Position, u.Position + rd * back);
if (back > 0.01f)
{
Vector2 start = u.Position;
Vector2 end = battle.Board.ClampInside(start + rd * back, u.Radius);
yield return Fx.MoveAlong(u.transform, start, end, cfg.moveSpeed, null);
u.Position = end;
o.Path.Add(end);
}
yield break;
}
Vector2 c = u.Position + rd * h;
NoteForced(u, u.Position, c);
if (h > 0.01f)
{
yield return Fx.MoveAlong(u.transform, u.Position, c, cfg.moveSpeed, null, false, recoil); // 밀려나는 속도를 가진 채 닿는다
u.Position = c;
o.Path.Add(c);
}
Face(u, foe.Position - u.Position); // 닿은 적 쪽으로 돌아 찌른다
o.Chains++;
o.Notes.Add("반작용 → " + foe.DisplayName);
ImpactExchange(u, foe, o);
if (!u.IsAlive) yield break;
float power = ImpactPower(recoil, h);
Vector2 n = foe.Position - u.Position;
n = n.sqrMagnitude > 1e-6f ? n.normalized : rd;
float push = power * cfg.spearPushRatio * SkillMods.PushMult(u, true) * PushTakenMult(foe);
bool pushedDone = true;
if (foe.IsAlive && push > 0.01f)
{
pushedDone = false;
Fx.Run(Track(Push(foe, n, push, u, o), () => pushedDone = true));
}
float next = Reach(u, u.Position, -n, power * cfg.collisionSelfBounceRatio * UnitHitKeep() * cfg.spearRecoilRatio * SkillMods.AxeBounce(foe));
if (chain > 0 && next > 0.01f && u.IsAlive) yield return SpearRecoil(u, -n, next, foe, chain - 1, o);
while (!pushedDone) yield return null;
battle.NotifyChanged();
}
// ---------- 기병: 관통(제자리 복귀 없음 · PD 2026-11-10) ----------
/// <summary>
/// 관통 돌격(기병 · 스킬로 관통하는 보병·창병): 유닛 무시(아군은 지나칠 수 없으면 직전 정지 · 손견·손책 = 아군도 통과) · 경로 위 적 피해·옆 밀기 ·
/// 손책 소패왕 = 전장 벽에서 핀볼처럼 튕겨 남은 거리 소진 · 반격 · 장애물 → 장료 요래(끌어오기) → 복귀(조운·손책·여포·문추·공손찬·순우경 · 하후돈 = 탭 지점·쓸어 감).
/// </summary>
/// <param name="slideExclude">빙판 미끄러짐 재실행(앞서 관통한 적 제외 · 끌어오기·복귀 없음) · null = 일반 행동.</param>
IEnumerator CavalryRoutine(Unit u, Vector2 origin, Vector2 dir, float dist, Vector2 target, bool moveOnly, ActionOutcome o, List<Unit> slideExclude = null)
{
bool slide = slideExclude != null;
bool passAll = !moveOnly && PierceAllies(u);
bool pinball = !moveOnly && !slide && SkillMods.Has(u, SkillKeys.WallBounce, true);
var hit = new List<Unit>();
Vector2 start = origin;
Vector2 d = dir;
float left = dist;
GimmickInstance gim = null;
Vector2 gNormal = -dir;
float gimLeft = 0f;
Face(u, dir);
for (int seg = 0; seg < 6 && left > 0.05f && u.IsAlive; seg++)
{
left = PassLossTravel(u, start, d, left, Combat.FreeTravel(u, start, d, left, false, false), slideExclude); // 유닛을 지날 때마다 남은 거리가 준다(PD 2026-11-16)
float travel = Combat.FreeTravel(u, start, d, left, false, false); // 유닛은 무시 · 벽·장애물 기믹만
if (!passAll) travel = StopBeforeUnclearedAllies(u, start, d, travel); // 지나칠 수 없는 아군 직전에서 멈춤
float gDist;
gim = BlockAhead(u, start, d, left, travel + 0.05f, out gDist, out gNormal); // 장애물 = 관통 불가 → 거기서 정지(PD #1097)
var dists = new List<float>();
var enemies = moveOnly ? new List<Unit>() : Combat.EnemiesOnPath(u, start, d, travel, dists);
if (slide)
for (int i = enemies.Count - 1; i >= 0; i--)
if (slideExclude.Contains(enemies[i]))
{
enemies.RemoveAt(i);
dists.RemoveAt(i);
}
Vector2 wallN;
bool bounce = false;
if (pinball && gim == null && travel < left - 0.1f)
{
Combat.BoardWallTravel(u, start, d, left, out wallN);
if (wallN.sqrMagnitude > 0.5f)
{
bounce = true;
gNormal = wallN;
}
}
Vector2 end = bounce ? start + d * travel : BackOffFromUnits(u, start, d, travel, passAll);
if (enemies.Count > 0 && u.View != null) u.View.PlayAttack();
float segTotal = Vector2.Distance(start, end), segDur = Fx.MoveDuration(segTotal, cfg.moveSpeed);
for (int i = 0; i < enemies.Count; i++) // 관통으로 닿을 적마다 닿는 시각(MoveAlong 감속 1−(1−k)² 의 역) — 호위가 함께 출발
{
float frac = segTotal > 1e-4f ? Mathf.Clamp01(dists[i] / segTotal) : 1f;
float eta = (1f - Mathf.Sqrt(1f - frac)) * segDur;
PreGuard(u, enemies[i], start + d * dists[i], eta);
var sk = SkillSystem.Current; // 기병 관통도 닿기 직전 이펙트(표 prehit · 마초 금빛 검기 · 2026-11-12 PD 「주창과 같은 검기 궤적이 반영되지 않음」 = 보병 첫 충돌·튕김에만 불리던 것)
if (sk != null && enemies[i].Faction != u.Faction) sk.PreHitFx(u, enemies[i], d, eta);
}
int idx = 0;
var segDir = d;
yield return Fx.MoveAlong(u.transform, start, end, cfg.moveSpeed, travelled =>
{
while (idx < enemies.Count && travelled >= dists[idx] - 0.01f)
{
PierceHit(u, enemies[idx], segDir, o, 1f);
hit.Add(enemies[idx]);
idx++;
}
});
u.Position = end;
o.Path.Add(end);
for (; idx < enemies.Count; idx++)
{
if (dists[idx] > travel + 0.01f) continue;
PierceHit(u, enemies[idx], segDir, o, 1f);
hit.Add(enemies[idx]);
}
gimLeft = ImpactPower(left, travel); // 지형에 부딪히는 힘(PD 2026-11-16 「기병은 지형에 닿으면 튕겨질 수 있어야」 · 그 전 = 남은 거리 → 지형 바로 앞까지 달리면 0)
left -= travel;
if (!bounce) break;
d = Vector2.Reflect(d, gNormal).normalized; // 소패왕: 전장 가장자리에서 튕겨 남은 거리를 마저 달림
start = end;
o.Notes.Add("튕김");
DashBegin(u, d);
Face(u, d);
}
DashEnd(u); // 관통 돌격 끝 = 돌진 이펙트 소멸(PD 2026-11-10)
if (hit.Count == 0) o.MovedOnly = true;
else yield return Fx.Wait(0.15f);
// 살아남은 근접 적의 반격(받는 반격 % · −100 % = 없음 → Combat.CounterDamage 가 0)
var countered = new HashSet<Unit>();
foreach (var e in hit)
{
if (!u.IsAlive) break;
if (!e.IsAlive || !UnitTypeInfo.IsMelee(e.Type) || !countered.Add(e)) continue;
int c = Combat.CounterDamage(cfg, e, u, rng, true);
if (c <= 0) continue;
if (!Sim.Active && e.View != null) // 반격하는 쪽 = 짧게 공격 자세(2026-11-19 PD 「기병이나 창병이 관우를 공격할 때 관우도 공격 포즈로 짧게 바뀌며 대응」)
{
e.View.SetFacing(u.Position - e.Position);
e.View.PlayCounter();
}
c = SkillSystem.Deal(u, c, e, HitKind.Counter);
o.CounterTaken += c;
Fx.Popup(u.Position, c.ToString(), new Color(1f, 0.45f, 0.45f));
battle.NotifyChanged();
yield return Fx.Wait(0.12f);
}
if (gim != null && u.IsAlive)
{
var sk0 = SkillSystem.Current;
if (sk0 != null && sk0.Ctx != null && sk0.Ctx.Actor == u) sk0.Ctx.HitTerrain = true;
yield return CavalryHitsGimmick(u, gim, gimLeft, gNormal, o, d); // d = 부딪힐 때 달리던 방향(바위 굴림)
yield break;
}
if (!u.IsAlive || moveOnly || slide) yield break;
if (hit.Count > 0 && SkillMods.Has(u, SkillKeys.DragBack, true)) yield return DragBack(u, origin, dir, hit, o); // 장료 요래
// 복귀: 항상(return_always) · 피해를 입혔을 때(return_on_hit) · 하후돈 맹장 = 거리와 무관하게 탭한 지점으로
var ra = SkillMods.First(u, SkillKeys.ReturnAlways, true);
var rh = hit.Count > 0 ? SkillMods.First(u, SkillKeys.ReturnOnHit, true) : null;
bool aim = SkillMods.Has(u, SkillKeys.ReturnAim, true);
if (ra == null && rh == null && !aim) yield break;
bool dmgBack = (ra != null && ra.P >= 0.5f) || (rh != null && rh.P >= 0.5f);
bool sweep = (ra != null && ra.Get(1) >= 0.5f) || (rh != null && rh.Get(1) >= 0.5f);
Vector2 dest = origin;
// 패시브 회군 돌파(return_on_hit 쓸어 감)는 액티브 맹장의 끌어 정한 복귀에도 적용(2026-11-20 PD 「회군 돌파를 액티브로 끌어 정한 복귀에도 적용되도록 복구」 ·
// 같은 날 앞 지시로 끄였던 것을 되돌림 = 복귀 길 위 적을 도착점 앞으로 함께 밀고 감)
if (aim)
{
var sk = SkillSystem.Current;
// 2026-11-20 PD 「하후돈의 스킬도 조조와 마찬가지로 스킬 시전 후 한번 더 슬링샷 조작이 가능해야」 = 탭 대신 하후돈에서 끌어 놓기(방향 · 거리 = 자기 슬링 최대까지)
if (sk != null)
yield return sk.WaitTap(u, SkillSystem.TapKind.Sling, u.Position, 0f, (o.SkillUsed != null ? o.SkillUsed.NameKo : "복귀") + " — 끌어 놓아 복귀할 곳을 정하세요", origin, w => dest = w, u);
}
yield return ReturnRoutine(u, dest, dmgBack, sweep, o);
}
/// <summary>복귀 이동: 유닛 무시 · 복귀 중 피해(조운·손책 소패왕) · 쓸어 감(하후돈 = 경로 위 유닛을 끝까지 함께 밀고 감 · 아군 포함).</summary>
IEnumerator ReturnRoutine(Unit u, Vector2 dest, bool dmgBack, bool sweep, ActionOutcome o)
{
yield return Fx.Wait(0.1f);
dest = battle.Board.ClampInside(dest, u.Radius);
Vector2 from = u.Position;
Vector2 rd = dest - from;
float len = rd.magnitude;
if (len < 0.05f) yield break;
Vector2 rdir = rd / len;
float travel = Combat.FreeTravel(u, from, rdir, len, false, false); // 벽·장애물에서 멈춤
var dists = new List<float>();
var onPath = Combat.UnitsOnPath(u, from, rdir, travel, dists);
Vector2 end = sweep ? from + rdir * travel : BackOffFromUnits(u, from, rdir, travel, true);
DashBegin(u, rdir);
Face(u, rdir);
int idx = 0;
yield return Fx.MoveAlong(u.transform, from, end, cfg.moveSpeed, t =>
{
while (idx < onPath.Count && t >= dists[idx] - 0.01f)
{
var e = onPath[idx++];
if (dmgBack && e.Faction != u.Faction)
{
if (SkillSystem.Current != null) SkillSystem.Current.VfxAllowRehit(e); // 나갈 때 맞은 적도 복귀 피해 때 피격 이펙트 다시(PD 2026-11-20 공손찬)
PierceHit(u, e, rdir, o, 1f);
}
}
});
u.Position = end;
o.Path.Add(end);
o.Returned = true;
DashEnd(u);
if (sweep)
{
// 쓸어 감: 경로 위 유닛을 도착점 앞(복귀 방향)으로 줄지어 민다
float off = u.Radius;
foreach (var e in onPath)
{
if (e == null || !e.IsAlive) continue;
Vector2 eFrom = e.Position;
off += e.Radius + 0.05f;
Vector2 eTo = battle.Board.ClampInside(end + rdir * off, e.Radius);
off += e.Radius;
Fx.Run(Fx.MoveAlong(e.transform, eFrom, eTo, cfg.moveSpeed, null));
e.Position = eTo;
o.Displaced.Add(new Displacement { Unit = e, From = eFrom, To = eTo });
if (!o.Pushed.Contains(e)) o.Pushed.Add(e);
}
if (onPath.Count > 0) o.Notes.Add("복귀하며 쓸어 감");
}
battle.NotifyChanged();
}
/// <summary>
/// 이각 약탈(end_blast · PD 2026-11-20 「돌진 종료 후 멈춘 위치에 추가 폭파 피해를 입히며, 입힌 피해의 50% 만큼의 피해를 회복」):
/// 멈춘 자리 반경 p2 적 전원 = 공격력 × p1 · 준 피해 합 × p3 자신 회복(그 스킬 heal 행) · 폭파 이펙트 = 그 스킬 blast 행 · 폭파 맞은 적 = 「스킬id_blast」 hit 행.
/// </summary>
void EndBlast(Unit u, SkillSystem skills, SkillEffect e, ActionOutcome o)
{
float r = e.Get(1, 3f);
string key = o.SkillUsed != null ? o.SkillUsed.Id : null;
if (!SkillVfx.Blast(u, u.Position, r)) Fx.Burst(u.Position, r, Fx.SplashColor);
int total = 0;
foreach (var t in battle.AliveUnits(u.Faction == Faction.Player ? Faction.Enemy : Faction.Player))
{
if (Vector2.Distance(t.Position, u.Position) - t.Radius > r) continue;
skills.VfxAllowRehit(t);
int d = skills.Hit(t, Combat.SkillDamage(cfg, u, t, e.P, battle.Rng), u, HitKind.Skill);
if (d <= 0) continue;
Fx.Popup(t.Position, d.ToString(), Color.white);
if (!string.IsNullOrEmpty(key)) SkillVfx.Play(u, key + "_blast", SkillVfx.EventHit, Vector2.zero, t);
total += d;
}
if (total > 0) o.Notes.Add("폭파");
int heal = Mathf.RoundToInt(total * e.Get(2, 0.5f));
if (heal > 0) skills.Heal(u, heal, u, key);
}
/// <summary>장료 요래: 관통으로 피해를 입힌 적을 출발 위치로 끌고 옴(가까운 적부터 출발점 · 뒤는 진행 방향으로 줄지음).</summary>
IEnumerator DragBack(Unit u, Vector2 origin, Vector2 dir, List<Unit> hit, ActionOutcome o)
{
var list = new List<Unit>();
foreach (var e in hit)
if (e != null && e.IsAlive && !list.Contains(e)) list.Add(e);
list.Sort((a, b) => Vector2.Distance(origin, a.Position).CompareTo(Vector2.Distance(origin, b.Position)));
float off = 0f;
bool any = false;
foreach (var e in list)
{
Vector2 from = e.Position;
Vector2 to = battle.Board.ClampInside(origin + dir * off, e.Radius);
off += e.Radius * 2f + 0.1f;
Fx.Run(Fx.MoveAlong(e.transform, from, to, cfg.moveSpeed * 1.2f, null));
e.Position = to;
o.Displaced.Add(new Displacement { Unit = e, From = from, To = to });
any = true;
}
if (any)
{
o.Notes.Add("끌고 옴");
yield return Fx.Wait(0.3f);
}
battle.NotifyChanged();
}
/// <summary>
/// 동탁 폭정: p1 초 동안 이동 속도로 직진 · 전장 가장자리·화면 가장자리(출발 순간 화면)·장애물에서 핀볼처럼 튕김 · 닿은 유닛(아군 포함)을 옆으로 p2 강하게 밀침 · 적 = 돌진 피해(반격 받음) · 자신은 튕기지 않음.
/// pushDist 를 넘기면 맹획 남만왕(push_through) = 그 거리(슬링 거리)만 직진 · 튕기지 않고 벽·장애물에서 멈춤 · 밀치기 = push_through p1.
/// </summary>
IEnumerator RampageRoutine(Unit u, Vector2 origin, Vector2 dir, ActionOutcome o, float pushDist = -1f)
{
bool push = pushDist >= 0f;
var e0 = SkillMods.First(u, push ? SkillKeys.PushThrough : SkillKeys.Rampage, true);
float total = push ? pushDist : cfg.moveSpeed * (e0 != null ? e0.P : 1f);
float force = push ? (e0 != null ? e0.P : 1.5f) : (e0 != null ? e0.Get(1, 1f) : 1f);
// 화면 가장자리 = 출발 순간 화면으로 고정(PD 2026-11-20 39차 「한번이라도 적 유닛과 부딪힌 경우 같은 튕김 각도로 아무것도 없는 지형을 계속 튕김」 =
// 카메라가 달리는 유닛을 따라가 구간마다 다시 잰 화면 끝이 늘 동탁 앞 반 화면에 있었음)
Rect view = new Rect();
bool hasView = !push && ScreenRect(out view);
var touched = new HashSet<Unit>();
Vector2 start = origin;
Vector2 d = dir;
float left = total;
Face(u, d);
if (u.View != null) u.View.PlayAttack();
for (int seg = 0; seg < 8 && left > 0.05f && u.IsAlive; seg++)
{
Vector2 n;
float travel = Combat.BoardWallTravel(u, start, d, left, out n);
// 화면 가장자리(PD 2026-11-20 「유닛에게는 튕겨지지 않지만 화면 가장자리나 맵 오브젝트에 닿을 경우 튕기게」 — 전장 벽이 화면 밖에 있으면(스킬 테스트 장면 = 벽 x ±10 · 화면 x ±5)
// 화면 밖으로 나가 보이지 않는 곳에서 튕겼음) · 맵 오브젝트(장애물 기믹)는 아래 BlockAhead 그대로
float sTravel;
Vector2 sN;
if (hasView && ScreenEdgeTravel(u, view, start, d, travel, out sTravel, out sN) && sTravel < travel)
{
travel = sTravel;
n = sN;
}
float gDist;
Vector2 gN;
var g = BlockAhead(u, start, d, left, travel + 0.05f, out gDist, out gN);
if (g != null)
{
travel = Mathf.Max(0f, gDist - Combat.Epsilon);
n = gN;
}
var dists = new List<float>();
var units = Combat.UnitsOnPath(u, start, d, travel, dists);
Vector2 end = start + d * travel;
int idx = 0;
var segDir = d;
yield return Fx.MoveAlong(u.transform, start, end, cfg.moveSpeed, t =>
{
while (idx < units.Count && t >= dists[idx] - 0.01f)
{
var x = units[idx++];
if (!x.IsAlive || !touched.Add(x)) continue;
RampageHit(u, x, segDir, force, o);
}
});
u.Position = end;
o.Path.Add(end);
left -= travel;
if (g != null && (push || (n.sqrMagnitude >= 0.5f && left > 0.05f)))
{
var sk = SkillSystem.Current;
if (sk != null && sk.Ctx != null) sk.Ctx.HitTerrain = true; // 맹획 = 지형물에 닿으면 재행동(reaction_on_terrain)
}
if (push || n.sqrMagnitude < 0.5f || left <= 0.05f) break;
d = Vector2.Reflect(d, n).normalized;
start = end;
o.Notes.Add("튕김");
DashBegin(u, d);
Face(u, d);
}
DashEnd(u);
u.Position = BackOffFromUnits(u, origin, d, 0f, true, u.Position);
if (touched.Count == 0) o.MovedOnly = true;
battle.NotifyChanged();
}
/// <summary>
/// 직교 카메라 화면 가장자리(유닛 반지름만큼 안쪽)까지 나아갈 수 있는 거리 · normal = 닿는 면의 안쪽 방향(동탁 폭정 튕김 · PD 2026-11-20).
/// 화면 안에서 출발할 때만 · 화면 밖에서 출발하거나 카메라가 없으면 false(전장 벽만).
/// </summary>
static bool ScreenRect(out Rect view)
{
view = new Rect();
var cam = Camera.main;
if (cam == null || !cam.orthographic) return false;
float hh = cam.orthographicSize, hw = hh * cam.aspect;
Vector2 c = cam.transform.position;
view = new Rect(c.x - hw, c.y - hh, hw * 2f, hh * 2f);
return true;
}
static bool ScreenEdgeTravel(Unit u, Rect view, Vector2 start, Vector2 d, float dist, out float travel, out Vector2 normal)
{
travel = dist;
normal = Vector2.zero;
float r = u.Radius;
float minX = view.xMin + r, maxX = view.xMax - r, minY = view.yMin + r, maxY = view.yMax - r;
if (start.x < minX || start.x > maxX || start.y < minY || start.y > maxY) return false;
float best = dist;
bool hit = false;
if (d.x > 1e-4f) { float t = (maxX - start.x) / d.x; if (t < best) { best = t; normal = Vector2.left; hit = true; } }
else if (d.x < -1e-4f) { float t = (minX - start.x) / d.x; if (t < best) { best = t; normal = Vector2.right; hit = true; } }
if (d.y > 1e-4f) { float t = (maxY - start.y) / d.y; if (t < best) { best = t; normal = Vector2.down; hit = true; } }
else if (d.y < -1e-4f) { float t = (minY - start.y) / d.y; if (t < best) { best = t; normal = Vector2.up; hit = true; } }
travel = Mathf.Max(0f, best - Combat.Epsilon);
return hit;
}
void RampageHit(Unit u, Unit x, Vector2 dir, float force, ActionOutcome o)
{
if (x.Faction != u.Faction)
{
ImpactExchange(u, x, o);
if (!u.IsAlive) return;
}
if (!x.IsAlive) return;
Vector2 side = new Vector2(-dir.y, dir.x);
float sign = Vector2.Dot(x.Position - u.Position, side) >= 0f ? 1f : -1f;
Vector2 from = x.Position;
Vector2 to = KnockTo(x, side * sign, force * SkillMods.KnockbackTakenMult(x, true));
Fx.Run(Fx.MoveAlong(x.transform, from, to, cfg.moveSpeed, null));
x.Position = to;
o.Displaced.Add(new Displacement { Unit = x, From = from, To = to });
if (!o.Pushed.Contains(x)) o.Pushed.Add(x);
}
void PierceHit(Unit cav, Unit e, Vector2 dir, ActionOutcome o, float dmgMult)
{
if (!e.IsAlive) return;
int dmg = SkillSystem.Deal(e, Combat.Damage(cfg, cav, e, false, rng, true, dmgMult), cav, HitKind.Attack);
o.Attacked.Add(e);
o.DamageDealt += dmg;
Fx.Popup(e.Position, dmg.ToString(), Color.white);
// 옆으로 밀어내기(거구 = 밀리지 않음)
Vector2 side = new Vector2(-dir.y, dir.x);
float sign = Vector2.Dot(e.Position - cav.Position, side) >= 0f ? 1f : -1f;
if (e.IsAlive)
{
float kb = cfg.cavalryKnockback * SkillMods.KnockbackTakenMult(e, true);
Vector2 from = e.Position;
Vector2 to = KnockTo(e, side * sign, kb); // 늪 0 · 빙판 × · 장애물·함정에서 멈춤 · 다리 → 강(PD #1097)
Fx.Run(Fx.MoveAlong(e.transform, e.Position, to, cfg.moveSpeed * 0.6f, null));
o.Displaced.Add(new Displacement { Unit = e, From = from, To = to });
}
battle.NotifyChanged();
}
/// <summary>아군은 관통(통과)하되 travel 안에 완전히 지나칠 수 없는 아군이 있으면 그 아군 직전까지로 줄인다.</summary>
float StopBeforeUnclearedAllies(Unit u, Vector2 origin, Vector2 dir, float travel)
{
float t = travel;
var allies = battle.AliveUnits(u.Faction);
for (int pass = 0; pass < 4; pass++)
{
float before = t;
foreach (var a in allies)
{
if (a == u) continue;
Vector2 rel = a.Position - origin;
float along = Vector2.Dot(rel, dir);
float lat = Mathf.Abs(rel.x * dir.y - rel.y * dir.x);
float sum = u.Radius + a.Radius;
if (lat >= sum || along + sum <= 0f) continue; // 경로와 겹치지 않음 · 뒤쪽
float half = Mathf.Sqrt(sum * sum - lat * lat);
float touch = along - half;
float clear = along + half;
if (t >= clear || t <= touch) continue; // 완전히 지나침 · 닿기 전에 멈춤
t = Mathf.Min(t, Mathf.Max(0f, touch - Combat.Epsilon));
}
if (Mathf.Approximately(before, t)) break;
}
return t;
}
/// <summary>종착점이 적(allies = 아군도)과 겹치면 경로를 되짚어 겹치지 않는 지점까지 물러선다 · at = 그 점에서 dir 반대로 되짚음.</summary>
Vector2 BackOffFromUnits(Unit u, Vector2 origin, Vector2 dir, float travel, bool allies, Vector2? at = null)
{
Vector2 p0 = at ?? origin + dir * travel;
float maxBack = at.HasValue ? 4f : travel;
for (float b = 0f; b <= maxBack + 1e-3f; b += 0.1f)
{
Vector2 p = p0 - dir * b;
bool overlap = false;
foreach (var e in battle.Units)
{
if (e == null || e == u || !e.IsAlive || (!allies && e.Faction == u.Faction)) continue;
if (Vector2.Distance(p, e.Position) < u.Radius + e.Radius - 0.01f)
{
overlap = true;
break;
}
}
if (!overlap) return p;
}
return at ?? origin;
}
// ---------- 궁병 · 책사: 투사체 사격 (PD 2026-11-05 #1087 ⑤⑥) ----------
/// <summary>궁병·책사 사격 계획 — 조준 미리보기(PreviewShot)와 실제 행동(ArcherRoutine)이 같은 계산을 쓴다.</summary>
public class ShotPlan
{
/// <summary>복도 탐색으로 고른 적(조준 방향 사거리 안의 첫 적) · null = 쏘지 않고 목표점까지 이동.</summary>
public Unit Target;
/// <summary>쏜다(타겟을 조준했거나 시전형 스킬의 자유 사격).</summary>
public bool Fires;
/// <summary>시전형(예약) 스킬의 자유 사격 = 조준 방향에 적이 없어도 조준한 자리(사거리 넘으면 최대 사거리)로 발사(PD 2026-11-13 「손건 화친 등 · 이동하지 말고 해당 위치로 발사」).</summary>
public bool FreeShot;
public Vector2 From;
/// <summary>투사체가 멈춘 지점(첫 피격 유닛에 닿은 곳 · 빗나가면 비행 끝).</summary>
public Vector2 To;
/// <summary>투사체가 처음 맞히는 유닛(아군 포함 · 관통 없음) = 책사 광역의 중심.</summary>
public Unit Hit;
/// <summary>첫 피격 = 타겟이고 최종 목표점 명중 → 크리티컬.</summary>
public bool Crit;
/// <summary>책사: 중심 주변 광역 대상(아군 포함 · 중심·쏜 책사 제외 · 가까운 순).</summary>
public readonly List<Unit> Splash = new List<Unit>();
/// <summary>책사 광역 반경(화공 배율 반영).</summary>
public float SplashRadius;
/// <summary>레이저(shot_laser)가 꿰뚫을 적 전원(가까운 순 · 미리보기 강조 · 2026-11-12 태사자).</summary>
public readonly List<Unit> Pierced = new List<Unit>();
/// <summary>백기습영: 쏘기 전에 목표점 쪽으로 이동하는 거리(0 = 없음).</summary>
public float Teleport;
public Vector2 Origin;
/// <summary>투사체를 막거나 맞은 기믹(덤불·바위·성문·성벽 = 막힘 · 폭약 수레 = 파괴 · PD #1097) · 유닛을 맞혔으면 null.</summary>
public GimmickInstance HitGimmick;
/// <summary>책사 광역이 터진다(중심 = 첫 피격 유닛 · 유닛 없이 덤불·수레에 막혔으면 그 자리).</summary>
public bool HasSplash;
public Vector2 SplashCenter;
/// <summary>책사 광역에 들어 지워질 기믹(덤불 제거 · 수레 파괴).</summary>
public readonly List<GimmickInstance> ClearGimmicks = new List<GimmickInstance>();
}
ShotPlan PlanShot(Unit u, Vector2 origin, Vector2 dir, Vector2 target)
{
var p = new ShotPlan { From = origin, To = origin, Origin = origin, SplashRadius = SkillMods.SplashRadius(u, cfg) };
float range = SkillMods.Range(u);
if (PowerAim(u)) // 플레이어 승병 시전형 스킬 = 사거리 안 첫 적을 찾아 겨누지 않고 당긴 세기만큼 날아감(그 길 위 첫 유닛에 맞음 · PD 2026-11-19 노숙·육손 「길이에 따라 스킬이 타겟팅 될 위치를 조절」)
{
AimFree(u, p, dir, target, range);
return p;
}
// 조준 방향으로 사거리 안의 첫 적 — 있으면 제자리 사격 · 없으면(사거리 밖 · 방향이 맞지 않음) 쏘지 않고 목표점까지 이동(PD 2026-11-16 「궁병이 이동과 동시에 공격하지 못하게」 · 그 전 = 사거리 밖 +비율 안의 적에게 다가가 사격). hitDist = 그 적 가장자리까지의 간격.
float hitDist;
p.Target = Combat.FirstEnemyOnPath(u, origin, dir, range, out hitDist);
if (p.Target == null && AimsAtAllies(u)) p.Target = Combat.FirstAllyOnPath(u, origin, dir, range, out hitDist); // 간옹 유세 = 적이 없으면 아군을 향해 쏨
if (p.Target == null)
{
if (ArmedActiveShot(u)) AimFree(u, p, dir, target, range); // 시전형(예약) 스킬 = 적이 없어도 조준한 자리로 발사(이동하지 않음)
else if (AimRules.DragMode && u.Faction == Faction.Player) // 끌기 조준(PD 2026-11-18): 판정 게이지 명중·치명타 칸 = 적이 없어도 제자리에서 그 방향으로 발사 · 최대 사거리에서 소멸(빈 칸 = 이동만은 moveOnly 로 따로)
AimFree(u, p, dir, origin + dir * (range + u.Radius + 1f), range);
return p;
}
Aim(u, p, dir, target, range);
return p;
}
/// <summary>
/// 사격 위치(p.From)에서 타겟 방향 투사체 · 비행 거리 = 사거리(쏜 유닛 가장자리부터) · 경로 위 첫 유닛이 맞는다(아군 포함 · 관통 없음 · 백발백중 = 아군 통과) ·
/// 막는 기믹(덤불·바위·성문·성벽) · 파괴되는 기믹(폭약 수레) · 안개 안 유닛 제외 · 책사 = 광역 계획(AimSplash).
/// </summary>
void Aim(Unit u, ShotPlan p, Vector2 dir, Vector2 target, float range)
{
p.Fires = true;
Vector2 aim = p.Target.Position - p.From;
Vector2 adir = aim.sqrMagnitude > 1e-6f ? aim.normalized : dir;
float travel;
bool passObstacles;
Faction? pass = ArrowPass(u, out passObstacles);
Combat.ArrowIgnoreGimmicks = passObstacles;
try
{
p.Hit = Combat.FirstUnitOnArrow(u, p.From, adir, range + u.Radius, cfg.arrowRadius, pass, out travel, out p.HitGimmick);
}
finally
{
Combat.ArrowIgnoreGimmicks = false;
}
p.To = p.From + adir * (p.Hit != null ? travel + cfg.arrowRadius : travel);
p.Crit = p.Hit == p.Target && Combat.EnemyAtPoint(u, target, cfg.finalHitTolerance) == p.Target; // 목표점 명중 크리(무조건 치명타 스킬 = 피해 계산에서)
if (AimRules.DragMode && u.Faction == Faction.Player) p.Crit = false; // 끌기 조준(PD 2026-11-18 테스트) = 아군 치명타는 판정 게이지 빨간 칸에서만
if (u.Type == UnitType.Strategist && !SkillMods.Has(u, SkillKeys.ShotSingle)) AimSplash(u, p); // 장로 = 직선 투사체(광역 없음)
}
/// <summary>
/// 장착(예약 → 조준 미리보기·행동 중)한 액티브 스킬에 아군 명중 회복(ally_hit_heal)이 있음 = 조준 방향에 적이 없으면 아군을 대상으로 쏜다
/// (PD 2026-11-13 「간옹의 스킬이 아군을 향해 발사되지 않음」 · 예전 = 경로 위 적이 없으면 쏘지 않고 이동만 · 패시브·시한 효과는 그대로).
/// </summary>
static bool AimsAtAllies(Unit u)
{
foreach (var h in SkillMods.Get(u, SkillKeys.AllyHitHeal))
if (!h.Passive && h.Timed == null) return true;
return false;
}
/// <summary>범위 회복(손건 화친 splash_heal) 스킬 중 전용 회복 이펙트(표 heal 행)가 있는 스킬 id · 없으면 null(공통 회복).</summary>
static string SplashHealFx(Unit u)
{
foreach (var h in SkillMods.Get(u, SkillKeys.SplashHeal))
if (h.Def != null && SkillVfx.Has(h.Def.Id, SkillVfx.EventHeal)) return h.Def.Id;
return null;
}
/// <summary>장착(예약 → 조준 미리보기·행동 중)한 다음 행동(next_action) 액티브가 있음 = 시전형 스킬 사격.</summary>
static bool ArmedActiveShot(Unit u)
{
var sys = SkillSystem.Current;
var s = sys != null ? sys.Of(u) : null;
return s != null && s.Armed && s.Active != null && s.Active.Trigger == SkillTrigger.NextAction;
}
/// <summary>
/// 시전형 스킬 자유 사격(PD 2026-11-13 「시전형 스킬은 스킬 발동 예약 후 슬링샷 조작하면 해당 위치로 발사 · 지금은 이동하고 있어(손건 화친 등)」):
/// 조준 방향으로 조준한 자리까지(사거리를 넘으면 최대 사거리) · 경로 위 첫 유닛·막는 기믹에 맞음 · 책사 = 맞으면 그 자리 광역 · 이동하지 않는다.
/// </summary>
void AimFree(Unit u, ShotPlan p, Vector2 dir, Vector2 target, float range)
{
p.Fires = true;
p.FreeShot = true;
float want = PowerAim(u) ? PowerReach(u, target, range + u.Radius) : Mathf.Clamp(Vector2.Dot(target - p.From, dir), 0.5f, range + u.Radius); // 플레이어 승병 = 당긴 세기만큼(PD 2026-11-19)
float travel;
bool passObstacles;
Faction? pass = ArrowPass(u, out passObstacles);
Combat.ArrowIgnoreGimmicks = passObstacles;
try
{
p.Hit = Combat.FirstUnitOnArrow(u, p.From, dir, want, cfg.arrowRadius, pass, out travel, out p.HitGimmick);
}
finally
{
Combat.ArrowIgnoreGimmicks = false;
}
p.To = p.From + dir * (p.Hit != null ? travel + cfg.arrowRadius : travel);
p.Crit = false;
if (u.Type == UnitType.Strategist && !SkillMods.Has(u, SkillKeys.ShotSingle)) AimSplash(u, p);
}
/// <summary>화살이 지나는 진영(황충 노익장·손권 강동의 주인 = 아군 통과 · p2 1 = 장애물도 통과).</summary>
static Faction? ArrowPass(Unit u, out bool obstacles)
{
obstacles = false;
bool any = false;
foreach (var h in SkillMods.Get(u, SkillKeys.ArrowPassAllies))
{
any = true;
if (h.E.Get(1) >= 0.5f) obstacles = true;
}
return any ? u.Faction : (Faction?)null;
}
IEnumerator ArcherRoutine(Unit u, Vector2 origin, Vector2 dir, float dist, Vector2 target, bool moveOnly, ActionOutcome o)
{
if (!moveOnly && HasSpecialShot(u))
{
yield return SpecialShot(u, origin, dir, target, o); // 장착 스킬 특수 사격(ActionResolver.Skills.cs)
yield break;
}
var p = moveOnly ? null : PlanShot(u, origin, dir, target);
if (p != null && p.Teleport > 0.01f)
{
yield return Move(u, p.Origin + dir * p.Teleport, o); // 백기습영: 목표점까지 이동 후 사격
if (p.Target == null) o.MovedOnly = true;
}
if (p == null || (p.Target == null && !p.FreeShot))
{
// 공격 가능 범위에 적이 없으면 목표점까지 이동 · 쏘지 않는다 (PD 2026-11-04 2차 지시 · #1087 ⑥ 유지) · 장애물 = 튕김 · 늪·고지 = 이동 비용(PD #1097)
if (p == null || p.Teleport <= 0.01f)
{
float reach = MoveReach(u, origin, dir, dist);
var arrive = MoveFxBegin(u, origin + dir * reach, dir); // 출발한 자리 · 도착한 자리의 이펙트(표 depart · arrive 행 · 2026-11-11 PD 「황충 이동 시 최초 이동 때와 도착할 때 먼지 연출」)
yield return MoveOrHit(u, origin, dir, reach, o);
MoveFxEnd(u, arrive, dir);
}
yield break;
}
if (!p.Fires)
{
o.MovedOnly = true; // 쏠 수 없음(안전 장치 · 타겟이 있으면 항상 쏜다)
yield break;
}
Face(u, p.To - p.From); // 제자리 사격도 쏘는 방향을 본다
yield return Shoot(u, p, o);
}
/// <summary>
/// 투사체 1발: 첫 피격 유닛에 사격 피해(아군이면 오사 · 상성 적용 · 반격 없음 · 명중 보상 없음 · 밀지 않으므로 규칙 ⑤ 없음)
/// → 책사는 그 자리 반경 안 다른 유닛 전원에게 광역(대상별 피해 × 광역 비율 · 같은 편은 × 아군 비율 · 크리 없음 · 화공·팔문 간파 반영).
/// </summary>
IEnumerator Shoot(Unit u, ShotPlan p, ActionOutcome o)
{
bool strategist = u.Type == UnitType.Strategist;
if (strategist) BattleEvents.Raise(BattleEvents.StrategistShots, u); // 보물 조건 효과(PD #1093 C)
o.Fired = true;
o.ShotHit = p.Hit;
if (u.View != null) u.View.PlayAttack();
if (p.Hit != null && SkillMods.Sum(u, SkillKeys.SplashHeal) <= 0f)
PreGuard(u, p.Hit, p.From, Fx.ArrowDuration(Vector2.Distance(p.From, p.To))); // 직격 대상의 호위가 화살과 함께 출발
yield return SkillVfx.Shot(u, p.From, p.To, strategist ? Fx.StrategistShotColor : Fx.ArrowColor); // 예약 스킬 투사체 행(shot)이 없으면 선 화살
SkillVfx.Blast(u, p.To, p.SplashRadius, SkillVfx.EventLand); // 투사체가 끝난 자리(명중 대상 · 최대 사정거리) 연출(표 land 행 · 손건 하트 · PD 2026-11-13)
if (p.Hit == null && SkillMods.Sum(u, SkillKeys.SplashHeal) > 0f)
{
// 손건 화친 = 명중하지 않아도 스킬이 끝난 자리에 범위 회복(적 포함 · PD 2026-11-13 「대상을 명중하지 않더라도 스킬이 종료된 위치에 범위 생명력 회복」)
float healMiss = SkillMods.Sum(u, SkillKeys.SplashHeal, true);
string healMissFx = SplashHealFx(u);
float rad = p.SplashRadius > 0f ? p.SplashRadius : SkillMods.SplashRadius(u, cfg);
if (!SkillVfx.Blast(u, p.To, rad)) Fx.Burst(p.To, rad, Fx.SplashColor);
var hsm = SkillSystem.Current;
int amtMiss = Mathf.RoundToInt(SkillSystem.AtkOf(u) * healMiss);
if (hsm != null)
foreach (var s in Combat.UnitsInCircle(p.To, rad, null, u))
if (s.IsAlive) hsm.Heal(s, amtMiss, u, healMissFx, healMissFx != null);
yield return Fx.Wait(0.1f);
yield break;
}
if (p.Hit == null && p.HitGimmick == null)
{
yield return Fx.Wait(0.1f); // 빗나감(벽 · 비행 끝)
yield break;
}
Vector2 center = p.HasSplash ? p.SplashCenter : p.To;
float healAll = SkillMods.Sum(u, SkillKeys.SplashHeal, true); // 손건 화친 = 피해 없이 회복만(PD #1112 결정 ⑧)
string healFx = healAll > 0f ? SplashHealFx(u) : null; // 그 스킬 heal 행 = 회복 대상마다 1번(적 포함 · 가득 차 있어도 · PD 2026-11-13 손건)
if (p.Hit != null)
{
if (healAll > 0f)
{
var hs = SkillSystem.Current;
if (hs != null) hs.Heal(p.Hit, Mathf.RoundToInt(SkillSystem.AtkOf(u) * healAll), u, healFx, healFx != null);
}
else if (p.Hit.Faction == u.Faction && AllyHitSpecial(u, p.Hit, p.From, o))
{
// 아군 명중 = 회복·버프(순욱·소교·간옹·미축) · 감녕 = 아군 곁으로 이동 후 재공격 — 피해 없음
}
else ShotDamage(u, p.Hit, Combat.Damage(cfg, u, p.Hit, p.Crit, rng, false), p.Crit, o);
}
else yield return ArrowHitsGimmick(u, p, o); // 덤불·성문 막힘 · 수레 파괴(PD #1097)
yield return ExtraArrows(u, p, o); // 하후연 삼연시(멀티샷) · 감녕 도탄
if (strategist && p.HasSplash)
{
yield return SplashGimmicks(u, p, o); // 덤불 제거 · 수레 파괴 · 화공 불(PD #1097)
// 손건 화친 = 명중 자리에 회복 광역 연출(표 blast 행 · 제갈량 칠성 기원 시전과 같은 고리·구름·십자 · PD 2026-11-13) · 행이 없으면 예전처럼 납작한 원
if (!(healAll > 0f && p.Hit != null && SkillVfx.Blast(u, center, p.SplashRadius))) Fx.Burst(center, p.SplashRadius, Fx.SplashColor);
if (healAll > 0f)
{
// 손건 화친: 광역 = 피해 대신 회복(적 포함 · 명중 대상은 위에서 회복)
int amt = Mathf.RoundToInt(SkillSystem.AtkOf(u) * healAll);
var sys = SkillSystem.Current;
foreach (var s in p.Splash)
if (s.IsAlive && sys != null) sys.Heal(s, amt, u, healFx, healFx != null);
}
else
{
float splashRatio = SkillMods.SplashRatio(u, cfg, true);
float allyRatio = SkillMods.SplashAllyRatio(u, cfg, true);
int splashTotal = 0;
foreach (var s in p.Splash)
{
if (!s.IsAlive) continue;
if (s.Faction == u.Faction && AllyHitSpecial(u, s, p.From, o, true)) continue; // 보급·경국지색 = 광역에 든 아군도 회복
float ratio = splashRatio * (s.Faction == u.Faction ? allyRatio : 1f);
int dmg = Combat.SplashDamage(cfg, u, s, ratio, rng);
if (dmg <= 0) continue;
int got = ShotDamage(u, s, dmg, false, o);
if (s.Faction != u.Faction) splashTotal += got;
}
SplashHealLowest(u, splashTotal); // 이각 약탈
}
}
battle.NotifyChanged();
yield return Fx.Wait(0.2f);
}
/// <summary>사격 피해 적용 + 집계(상대 = Attacked · 같은 편 = FriendlyHit 오사). 반환 = 실제 피해.</summary>
int ShotDamage(Unit a, Unit d, int dmg, bool crit, ActionOutcome o, HitKind kind = HitKind.Attack)
{
crit |= Combat.LastCrit;
dmg = SkillSystem.Deal(d, dmg, a, kind);
if (d.Faction == a.Faction)
{
o.FriendlyHit.Add(d);
o.FriendlyDamage += dmg;
Fx.Popup(d.Position, dmg + " 오사", Fx.FriendlyFireColor);
return dmg;
}
o.Attacked.Add(d);
o.DamageDealt += dmg;
o.Crit |= crit;
if (crit && a.Type == UnitType.Archer) BattleEvents.Raise(BattleEvents.ArcherCrits, a); // 보물 조건 효과(PD #1093 C)
Fx.Popup(d.Position, crit ? dmg + "!" : dmg.ToString(), crit ? new Color(1f, 0.7f, 0.2f) : Color.white);
return dmg;
}
// ---------- 공통 ----------
IEnumerator MoveFree(Unit u, Vector2 origin, Vector2 dir, float dist, ActionOutcome o)
{
float free = Combat.FreeTravel(u, origin, dir, dist, true, true);
yield return Move(u, origin + dir * free, o);
o.MovedOnly = true;
}
/// <summary>슬링샷 직진 구간 끝 · 새 이동 구간 시작 = 돌진 이펙트(skill_vfx.csv travel) 소멸 · 다시 재생(PD 2026-11-10).</summary>
static void DashEnd(Unit u)
{
var s = SkillSystem.Current;
if (s != null) s.DashEnd(u);
}
static void DashBegin(Unit u, Vector2 dir)
{
var s = SkillSystem.Current;
if (s != null) s.DashBegin(u, dir);
}
/// <summary>
/// 등속 접근(MoveStraight)으로 적 target 에 닿기 직전 이펙트(skill_vfx.csv prehit 행 · 닿는 시각 = 이 접근의 이동 시간 · PD 2026-11-12 「적과 닿기 직전 적에게 베기」) —
/// 보병 돌진 첫 충돌 · 튕김 연쇄 충돌에서 부름(창·기병 관통 · 궁병 사격에는 아직 없음). 아군이면 내지 않는다.
/// </summary>
void PreHit(Unit u, Unit target, Vector2 contact, float launch)
{
var s = SkillSystem.Current;
if (s == null || u == null || target == null || target.Faction == u.Faction) return;
float eta = Fx.ApproachDuration(Vector2.Distance(u.Position, contact), launch, cfg.moveSpeed);
s.PreHitFx(u, target, contact - u.Position, eta);
s.PreGuard(u, target, contact, eta); // 호위(관평)가 적 접근과 함께 출발 → 닿는 순간 대상 앞(2026-11-12 PD)
}
/// <summary>적 target 에 eta 초 뒤 확정으로 닿는 공격(창병 첫 충돌 · 기병 관통 · 궁병·책사 직격) — 호위가 적 움직임과 함께 출발(SkillSystem.PreGuard · 2026-11-12 PD).</summary>
static void PreGuard(Unit u, Unit target, Vector2 attackFrom, float eta)
{
var s = SkillSystem.Current;
if (s != null && u != null && target != null && target.Faction != u.Faction) s.PreGuard(u, target, attackFrom, eta);
}
/// <summary>출발·도착 이펙트를 낼 최소 이동 거리(월드 · 이보다 짧으면 제자리로 봄).</summary>
const float MoveFxMin = 0.05f;
/// <summary>도착으로 보는 남은 거리 비율 — 감속 이동은 마지막 10 % 거리를 전체 시간의 1/3 동안 천천히 가서, 이동이 끝난 뒤에 내면 먼지가 눈에 띄게 늦다(2026-11-11 실측 0.4초).</summary>
const float ArriveNear = 0.1f;
/// <summary>실제 이동 구간의 출발·도착 이펙트(skill_vfx.csv depart · arrive 행).</summary>
static void MoveFx(Unit u, string evt, Vector2 dir)
{
var s = SkillSystem.Current;
if (s != null) s.MoveFx(u, evt, dir);
}
/// <summary>도착 이펙트를 이미 냈는지(지켜보는 쪽과 이동이 끝난 쪽이 함께 봄).</summary>
class ArriveState
{
public Vector2 From;
public bool Moving;
public bool Done;
}
/// <summary>이동 시작: 실제로 움직일 거리면 출발 이펙트를 내고, 목적지에 거의 닿는 순간 도착 이펙트를 내도록 지켜본다.</summary>
ArriveState MoveFxBegin(Unit u, Vector2 dest, Vector2 dir)
{
var st = new ArriveState { From = u.Position };
st.Moving = Vector2.Distance(st.From, dest) > MoveFxMin;
if (!st.Moving || Sim.Active) return st;
MoveFx(u, SkillVfx.EventDepart, dir);
Fx.Run(ArriveWatch(u, dest, dir, st));
return st;
}
/// <summary>이동 끝: 지켜보던 쪽이 아직 못 냈으면(막혀서 목적지 근처에 못 감) 실제로 움직였을 때만 도착 이펙트.</summary>
void MoveFxEnd(Unit u, ArriveState st, Vector2 dir)
{
if (st.Done) return;
st.Done = true;
if (st.Moving && (u.Position - st.From).sqrMagnitude > MoveFxMin * MoveFxMin) MoveFx(u, SkillVfx.EventArrive, dir);
}
static IEnumerator ArriveWatch(Unit u, Vector2 dest, Vector2 dir, ArriveState st)
{
float near = Vector2.Distance(st.From, dest) * ArriveNear;
while (!st.Done && u != null && u.transform != null)
{
if (Vector2.Distance(u.transform.position, dest) <= near)
{
st.Done = true;
MoveFx(u, SkillVfx.EventArrive, dir);
yield break;
}
yield return null;
}
}
/// <summary>보는 방향 갱신(PD #1082 · 마지막 이동 방향 · 4방향 = 앞/뒤 세트 + 좌우 반전).</summary>
static void Face(Unit u, Vector2 dir)
{
if (u != null && u.View != null && dir.sqrMagnitude > 1e-6f) u.View.SetFacing(dir);
}
IEnumerator Move(Unit u, Vector2 to, ActionOutcome o, bool face = true)
{
if (face) Face(u, to - u.Position);
yield return Fx.MoveAlong(u.transform, u.Position, to, cfg.moveSpeed, null);
u.Position = to;
o.Path.Add(to);
}
/// <summary>등속 접근(감속 없음) — 부딪히는 순간까지 속도를 유지해 충돌 반응이 바로 이어진다.</summary>
/// <summary>
/// 부딪히는 힘(PD 2026-11-16 「알까기·당구처럼 미는 힘에 맞춰 세게 날아가 세게 부딪히게」): 쏜 거리 launch 에서, 부딪히기까지 간 거리 travelled × impactFalloff 만큼만 뺀다
/// (그 전 = 남은 거리 launch − travelled → 멀리 있는 상대일수록 힘이 0 에 가까웠다). 밀어내기 · 자기 튕김 · 창병 밀치기 · 바위 굴리기 · 연쇄가 이 값을 쓴다.
/// 이동 연출(Fx.MoveAlong 의 launch)도 같은 식이라 부딪히는 순간의 속도가 밀려나는 유닛의 출발 속도로 이어진다.
/// </summary>
float ImpactPower(float launch, float travelled)
{
return Mathf.Max(0f, launch - Mathf.Clamp01(cfg.impactFalloff) * Mathf.Max(0f, travelled));
}
/// <summary>밀리는 쪽 배율 = 병종 밀림 가중치(창병·기병 = 덜 밀림 · PD 2026-11-16 · BalanceConfig.unitStats.pushTakenRatio) × 스킬(거구 등 knockback_taken_pct) — 보병·창병의 공격과 연쇄 밀기에 쓴다.</summary>
static float PushTakenMult(Unit t)
{
return t.PushTaken * SkillMods.KnockbackTakenMult(t, true);
}
/// <summary>유닛에 부딪혀 상대를 밀어낸 뒤 남는 힘의 비율 = 1 − unitHitBounceLossRatio(PD 2026-11-16 「보병도 부딪힐 때 튕기는 거리가 약간씩은 줄어야」) — 보병 튕김·창병 반작용.</summary>
float UnitHitKeep()
{
return 1f - Mathf.Clamp01(cfg.unitHitBounceLossRatio);
}
/// <summary>
/// 기병 관통 감쇠(PD 2026-11-16 「적이나 아군을 통과할 때마다 이동 거리가 줄어들어야 · 알까기에서 다른 돌을 밀 때의 반발력」):
/// 경로 위 유닛(적·아군 · 가까운 순)을 하나 지날 때마다 그 뒤에 남은 거리 × (1 − cavalryPassLossRatio) → 줄어든 총 이동 거리. reach = 벽·장애물까지의 거리(그 너머 유닛은 세지 않는다).
/// </summary>
float PassLossTravel(Unit u, Vector2 origin, Vector2 dir, float dist, float reach, List<Unit> exclude = null)
{
float loss = Mathf.Clamp01(cfg.cavalryPassLossRatio);
if (loss <= 0f || dist <= 0f) return dist;
var dists = new List<float>();
var units = Combat.UnitsOnPath(u, origin, dir, Mathf.Min(dist, reach + 0.05f), dists);
float t = dist;
for (int i = 0; i < units.Count; i++)
{
if (exclude != null && exclude.Contains(units[i])) continue;
if (dists[i] >= t) break; // 줄어든 거리로는 닿지 않는다
t = dists[i] + (t - dists[i]) * (1f - loss);
}
return t;
}
/// <summary>to 에서 부딪히는 직진: launch = 쏜 거리(힘) → 그 힘의 속도로 출발해 속도를 가진 채 닿는다 · launch 0 = 등속.</summary>
IEnumerator MoveStraight(Unit u, Vector2 to, ActionOutcome o, float launch = 0f)
{
Face(u, to - u.Position);
yield return Fx.MoveAlong(u.transform, u.Position, to, cfg.moveSpeed, null, false, launch);
u.Position = to;
o.Path.Add(to);
}
/// <summary>부딪힌 순간의 피해 교환(연출 대기 없음): 공격 피해 → 상대가 살아 있으면 반격 피해. 결과는 행동 유닛 요약에 집계. 반환 = 준 피해.</summary>
int ImpactExchange(Unit a, Unit d, ActionOutcome o)
{
if (a.View != null) a.View.PlayAttack();
int raw = Combat.Damage(cfg, a, d, false, rng, true);
bool crit = Combat.LastCrit;
int dmg = SkillSystem.Deal(d, raw, a, HitKind.Attack);
o.Attacked.Add(d);
o.DamageDealt += dmg;
o.Crit |= crit;
Fx.Popup(d.Position, crit ? dmg + "!" : dmg.ToString(), crit ? new Color(1f, 0.7f, 0.2f) : Color.white);
if (d.IsAlive && a.IsAlive)
{
int c = Combat.CounterDamage(cfg, d, a, rng, true); // 부딪혀 밀리는 쪽의 반격(받는 반격 % · 반격 피해 %)
if (c > 0)
{
if (d.View != null) d.View.PlayAttack();
c = SkillSystem.Deal(a, c, d, HitKind.Counter);
o.CounterTaken += c;
Fx.Popup(a.Position, c.ToString(), new Color(1f, 0.45f, 0.45f));
}
}
battle.NotifyChanged();
return dmg;
}
/// <summary>
/// 알까기 양쪽 튕김(동시 시작): 부딪힌 유닛 = n 방향(중심을 잇는 선 · 당구 공처럼) · 남은 힘 × collisionPushRatio × 밀기 배율(청룡도 지기·호치·함진영) × 대상 밀림 배율(거구)
/// / 행동 유닛 = 들어온 방향 inDir 을 접촉면에 거울 반사한 방향(PD 2026-11-10 「IB 와 같이 비스듬히 맞으면 거울처럼 꺾여 나가야 해(당구처럼)」 · IB ActiveSkillSlingShot.ResolveCollisions 의
/// Vector3.Reflect(진행 방향, 중심선) · 정면 충돌 = 곧장 뒤로 · inDir 없음 = −n) · max(남은 힘, 슬링 최대 × 하한) × collisionSelfBounceRatio × 자기 튕김 배율(인덕·호치 = 0).
/// impactDmg = 함진영 충돌 추가 피해 기준.
/// chain = 유닛과 부딪힌 뒤의 튕김(적 = PD #1098 · 처음 닿은 유닛이 아군인 경우도 같다 = PD 2026-11-17): 튕겨나는 길에 다른 적이 있으면 그 적과 피해·반격 교환 → 그 적 기준으로 다시 튕김 · 아군이면 밀어내고 그 아군에게서도 다시 튕김 — 남은 연쇄 횟수(chain)가 0 이 되거나 힘이 다할 때까지(PD 2026-11-16 「강한 파워로 공격해서 추가 튕김이 발생하면 여러 번 공격」 · 그 전 = 연쇄 1회 · 아군이면 밀기만 하고 정지) · 같은 유닛과 다시 부딪힐 수 있다.
/// </summary>
IEnumerator Bounce(Unit striker, Unit struck, Vector2 n, float remaining, ActionOutcome o, int impactDmg, int chain = 0, Vector2 inDir = default(Vector2))
{
bool struckDone = true;
float force = struck != null ? remaining * cfg.collisionPushRatio * SkillMods.PushMult(striker, true) * PushTakenMult(struck) : 0f;
if (repeatPushCap > 0f && struck != null && struck.Faction != striker.Faction) force = Mathf.Min(force, repeatPushCap); // 연환격 첫 타격 밀림 한도(보병형이 이 스킬을 쓸 때 · 자기 튕김은 따로)
if (struck != null && struck.IsAlive && force >= 0.01f)
{
struckDone = false;
Fx.Run(Track(Push(struck, n, force, striker, o), () => struckDone = true));
}
Vector2 bd = BounceDir(inDir, n);
// 자기 튕김 × 자기 배율(허저 ×2 · 전위·맹획 0) × 서황 대부(도끼가 도는 서황을 친 유닛 = ×p3)
// 튕김 힘 = max(남은 거리, 슬링 최대 × 하한 비율)(PD 2026-11-10 「보병이 부딪힌 뒤 튕기는 거리가 너무 짧다 · IB 체크」): IB 는 이동 거리가 당김과 무관한 고정값이고
// 부딪히면 남은 거리를 전부 가진 채 반사(ActiveSkillSlingShot.ResolveCollisions · Unit.Shoot) → 여기는 당긴 만큼만 가서 적 바로 앞을 노리면 남은 거리가 거의 0 이라 튕김이 짧았음
float power = Mathf.Max(remaining, SkillMods.SlingMax(striker) * cfg.collisionSelfBounceMinRatio);
float self = Reach(striker, striker.Position, bd, power * cfg.collisionSelfBounceRatio * (struck != null ? UnitHitKeep() : 1f) * SkillMods.SelfBounceMult(striker, true) * (striker.Faction != (struck != null ? struck.Faction : striker.Faction) ? SkillMods.AxeBounce(struck) : 1f)); // 유닛에 부딪혔으면 상대를 밀어내며 잃은 힘만큼 덜 튕긴다(지형 = 그대로 · PD 2026-11-16)
if (self >= 0.01f && striker.IsAlive && chain >= 0)
{
// 연쇄(PD #1098): 튕겨나는 길의 첫 유닛(벽·장애물보다 앞) — 적 = 피해·반격 교환 후 다시 튕김 · 아군 = 밀고 다시 튕김
// 연쇄 한도(chain 0 · 지형에 부딪혀 튕길 때 포함)를 다 쓴 마지막 튕김도 적과 닿으면 피해를 준다(PD 2026-11-19 「튕기는 횟수만큼 공격 · 일정 횟수가 넘어가면 피해를 주지 않는다」 ·
// 그 전 = 한도 뒤 튕김은 적 앞에서 멈추기만) → 피해·반격 교환 후 그 적을 밀어내고 닿은 자리에서 정지(더 튕기지 않음)
float h2;
Unit second = Combat.FirstUnitOnPathExcept(striker, striker.Position, bd, self, struck, out h2);
if (second != null && (chain > 0 || (second.Faction != striker.Faction && !second.Npc)) && h2 <= Combat.FreeTravel(striker, striker.Position, bd, self, false, false) + Combat.Epsilon)
{
Vector2 c2 = striker.Position + bd * h2;
PreHit(striker, second, c2, self);
yield return MoveStraight(striker, c2, o, self);
while (!struckDone) yield return null; // 앞서 밀린 유닛이 멈춘 뒤에 다음 충돌을 계산한다(되돌아와 같은 유닛과 다시 부딪힐 수 있다)
float rem2 = ImpactPower(self, h2); // 연쇄도 같은 힘 계산(튕겨 가며 간 거리 × impactFalloff 만 빠짐)
Vector2 n2 = second.Position - c2;
n2 = n2.sqrMagnitude > 1e-6f ? n2.normalized : bd;
if (second.Faction != striker.Faction)
{
o.Chains++;
o.Notes.Add("연쇄 → " + second.DisplayName);
int imp2 = ImpactExchange(striker, second, o);
if (striker.IsAlive && chain > 0) yield return Bounce(striker, second, n2, rem2, o, imp2, chain - 1, bd);
else if (striker.IsAlive && second.IsAlive)
{
float f2 = rem2 * cfg.collisionPushRatio * SkillMods.PushMult(striker, true) * PushTakenMult(second); // 마지막 튕김 = 밀기만(자기 튕김 없음)
if (repeatPushCap > 0f) f2 = Mathf.Min(f2, repeatPushCap);
if (f2 >= 0.01f) yield return Push(second, n2, f2, striker, o);
}
}
else
{
// 아군 = 밀어내고 그 아군에게서도 다시 튕긴다(PD 2026-11-16 「아군과 닿아 튕겨서 추가로 적을 공격할 수 있어야」 · 그 전 = 밀기만 하고 정지)
yield return Bounce(striker, second, n2, rem2, o, 0, chain - 1, bd);
if (second.IsAlive) yield return PushedAllyAttack(second, o, striker);
}
while (!struckDone) yield return null;
yield break;
}
}
if (self >= 0.01f && striker.IsAlive)
{
float back = Combat.FreeTravel(striker, striker.Position, bd, self, true, true, struck);
NoteForced(striker, striker.Position, striker.Position + bd * back);
if (back > 0.01f)
{
Face(striker, bd); // 튕겨 나온 방향을 본다(PD #1082)
Vector2 end = battle.Board.ClampInside(striker.Position + bd * back, striker.Radius);
yield return Fx.MoveAlong(striker.transform, striker.Position, end, cfg.moveSpeed, null);
striker.Position = end;
o.Path.Add(end);
}
}
while (!struckDone) yield return null;
}
/// <summary>
/// 튕김 방향: 들어온 방향을 접촉면(중심선 n)에 거울 반사(IB Vector3.Reflect · 당구) — 비스듬히 맞을수록 옆으로 꺾여 나가고 정면 충돌 = 곧장 뒤로(−n).
/// 들어온 방향이 없거나 접촉면 쪽으로 가고 있지 않으면 −n.
/// </summary>
public static Vector2 BounceDir(Vector2 inDir, Vector2 n)
{
if (inDir.sqrMagnitude < 1e-6f) return -n;
Vector2 d = inDir.normalized;
if (Vector2.Dot(d, n) <= 1e-3f) return -n;
return Vector2.Reflect(d, n).normalized;
}
static IEnumerator Track(IEnumerator inner, System.Action onDone)
{
yield return inner;
onDone();
}
/// <summary>부딪힌 유닛을 n 방향으로 force 만큼 밀어낸다(다른 유닛·벽에 닿으면 멈춤). 밀어 주는 유닛(pusher)은 막는 것으로 보지 않는다. onEnd(true) = 다 못 가고 막힘.</summary>
IEnumerator Push(Unit target, Vector2 n, float force, Unit pusher, ActionOutcome o, System.Action<bool> onEnd = null, int chain = 0)
{
if (target == null || !target.IsAlive || force < 0.01f) yield break;
if (chain == 0 && pusher != null && pusher.Faction != target.Faction) BattleEvents.Raise(BattleEvents.Pushes, pusher); // 보물 조건 효과(PD #1093 C) · 연쇄로 밀린 것은 세지 않음
force = Reach(target, target.Position, n, force); // 늪 = 밀리는 거리도 이동 비용(PD #1097)
float slide = Combat.FreeTravel(target, target.Position, n, force, true, true, pusher);
// 연쇄 밀기(PD 2026-11-13 「슬링샷으로 적을 공격했을 때 다른 유닛에게 막힐 경우 다른 유닛도 물리적인 힘에 의해 튕겨질 수 있도록(당구처럼) · 밀리는 유닛이 증가할수록 밀리는 힘은 줄어들어야 ·
// A 유닛을 타격해 밀린 유닛이 B유닛을 미는 경우 A유닛이 밀리는 거리만큼이 슬링샷으로 밀었을 때 밀리는 거리처럼 동작」):
// 공격으로 밀린 유닛(민 쪽의 상대 진영 · 또는 이미 연쇄 중)이 가는 길을 다른 유닛이 막으면, 닿은 뒤 남은 밀림 거리 = 슬링샷의 남은 힘처럼 그 유닛을 민다
// (× collisionPushRatio × 그 유닛의 밀림 배율 · 방향 = 두 유닛 중심을 잇는 선) — 닿기까지 쓴 거리만큼 힘이 줄어 뒤로 갈수록 덜 밀림 · 아군을 밀어 공격시키는 규칙 ⑤(같은 편 밀기)는 그대로
Unit blocker = null;
if (slide < force - Combat.Epsilon * 2f && chain < MaxPushChain && (chain > 0 || (pusher != null && pusher.Faction != target.Faction)))
{
// 민 유닛은 맞닿아 있어 경로 검사 맨 앞(거리 0)에 잡힌다 → 빼고 찾는다 · 벽·기믹이 먼저면 그 거리(slide)보다 멀어 제외됨
float hitDist;
var b = Combat.FirstUnitOnPathExcept(target, target.Position, n, force, pusher, out hitDist);
if (b != null && b.IsAlive && !b.Npc && hitDist <= slide + Combat.Epsilon + 0.05f) blocker = b;
}
// 밀린 아군의 충돌(PD 2026-11-18 「알까기와 동일하게 물리적으로 튕기며 즉시 피해 · 멈춘 뒤 견제처럼 공격하는 것이 아니라」):
// 같은 편에게 밀린 유닛이 가는 길에서 상대 유닛에 막히면 → 속도를 가진 채 닿고 그 순간 피해·반격 교환 → 알까기 튕김(Bounce · 상대 밀림 + 자기 튕김 · 연쇄)
// 그 전 = 막힌 자리에서 멈춘 뒤(밀기 끝) 0.1초 뒤 찌르기 공격(규칙 ⑤ PushedAllyAttack) — 이제 그 공격은 충돌이 없었던 경우에도 하지 않는다(늘 물리 충돌로만)
// 연쇄로 밀린 행동 진영 유닛도 같다(PD 2026-11-19 「밀린 아군이 적과 닿은 경우 언제든 추가 피해」 · 예: 친 적이 밀려 아군을 밀고 그 아군이 다른 적과 부딪힘 ·
// 그 전 = 같은 편에게 직접 밀린 경우(chain 0)만 → 연쇄로 밀린 아군은 적을 밀기만 하고 피해 없음) · 행동 유닛 자신은 제외(자기 루틴으로 움직이는 중)
Unit foeHit = null;
bool sideImpact = pusher != null && (chain == 0 ? pusher.Faction == target.Faction : acting != null && target != acting && target.Faction == acting.Faction);
if (sideImpact && slide < force - Combat.Epsilon * 2f)
{
float fd;
var fb = Combat.FirstUnitOnPathExcept(target, target.Position, n, force, pusher, out fd);
if (fb != null && fb.IsAlive && !fb.Npc && fb.Faction != target.Faction && fd <= slide + Combat.Epsilon + 0.05f) foeHit = fb;
}
if (foeHit != null) blocker = null; // 부딪힌 상대 = 충돌(피해 + 알까기 튕김)로 처리 · 연쇄 밀기와 겹치지 않게
if (blocker == null && foeHit == null && slide < force - Combat.Epsilon * 2f && pusher != null && pusher.Faction != target.Faction)
ModeBattleRules.RaiseSlam(target, pusher); // 벽 · 장애물에 막힘(컨텐츠 모드 과제 「밀어내기」 · 2026-11-17)
NoteForced(target, target.Position, target.Position + n * slide); // 강제 이동 기록 → 강가·다리에서 밀려 강물에 들면 빠짐
float moved = 0f;
if (slide > 0.01f)
{
Face(target, n); // 밀린 방향을 본다(PD #1082)
Vector2 start = target.Position;
Vector2 end = battle.Board.ClampInside(target.Position + n * slide, target.Radius);
if (foeHit != null) yield return Fx.MoveAlong(target.transform, target.Position, end, cfg.moveSpeed, null, false, force); // 속도를 가진 채 부딪힘(MoveStraight 와 같은 출발 속도)
else yield return Fx.MoveAlong(target.transform, target.Position, end, cfg.moveSpeed, null);
target.Position = end;
moved = Vector2.Distance(start, end);
o.Displaced.Add(new Displacement { Unit = target, From = start, To = end });
}
o.Pushed.Add(target);
battle.NotifyChanged();
if (foeHit != null && foeHit.IsAlive && target.IsAlive)
{
pushImpacted.Add(target);
yield return PushedImpact(target, foeHit, n, ImpactPower(force, moved), o, pusher.Faction == target.Faction ? pusher : acting); // 민 유닛 = 같은 편(연쇄로 상대에게 밀렸으면 행동 유닛)
}
if (blocker != null && blocker.IsAlive)
{
float f2 = ImpactPower(force, moved) * cfg.pushChainRatio * PushTakenMult(blocker); // 밀려가다 부딪힌 힘도 같은 계산(PD 2026-11-16) · 전달 비율 = pushChainRatio(병종의 미는 비율과 따로)
Vector2 n2 = blocker.Position - target.Position;
n2 = n2.sqrMagnitude > 1e-6f ? n2.normalized : n;
if (f2 >= 0.05f) yield return Push(blocker, n2, f2, target, o, null, chain + 1);
}
if (onEnd != null) onEnd(moved < force - Combat.Epsilon * 2f);
}
/// <summary>연쇄 밀기가 이어지는 최대 유닛 수(안전 한도 — 힘은 닿을 때마다 줄어 보통 그 전에 끝남).</summary>
const int MaxPushChain = 6;
/// <summary>
/// 규칙 ⑤: 밀린 아군이 상대 유닛과 닿아 있으면 그 자리에서 공격(근접 · 자기 행동 소모 없음) — 기본 1회 ·
/// 민 유닛의 군령(pushed_ally_attack_count = n 회) · 대장군(pushed_ally_attack_on_push = +n 회).
/// </summary>
IEnumerator PushedAllyAttack(Unit ally, ActionOutcome o, Unit pusher)
{
// 2026-11-18 PD 「멈춘 뒤 견제 공격이 발동하듯 공격 ✕ · 늘 물리적으로 즉시 튕겨지며 피해」 → 밀린 아군의 공격 = 밀리는 길의 충돌(Push → PushedImpact)만 · 멈춘 뒤 찌르기 공격은 없음
yield break;
}
/// <summary>이번 행동에서 밀리다 상대와 부딪혀 공격한 같은 편 유닛(테스트 · 표시 확인용).</summary>
readonly HashSet<Unit> pushImpacted = new HashSet<Unit>();
public bool WasPushImpacted(Unit u)
{
return u != null && pushImpacted.Contains(u);
}
/// <summary>
/// 밀린 같은 편 유닛 a 가 상대 d 와 부딪힌 순간(PD 2026-11-18 알까기): 피해·반격 즉시 교환(장합 교변 · 자기 밀림 배율 · 민 유닛의 간접 명중 상태 = 예전 밀린 공격과 같음)
/// → 알까기 튕김(d 밀림 + a 튕김 + 연쇄 · Bounce). 행동 유닛의 경로(o.Path)를 더럽히지 않게 따로 받은 결과를 합친다(a 의 이동 = Displaced).
/// </summary>
IEnumerator PushedImpact(Unit a, Unit d, Vector2 inDir, float power, ActionOutcome o, Unit pusher)
{
Face(a, d.Position - a.Position);
if (a.View != null) a.View.PlayAttack();
float scale = SkillMods.Product(a, SkillKeys.SelfPushedMult, true);
if (pusher != null && pusher != a && a.Atk > 0)
{
float add = SkillMods.Sum(pusher, SkillKeys.PushedAllyAtkAdd, true);
if (add > 0f) scale *= 1f + add * SkillSystem.AtkOf(pusher) / Mathf.Max(1f, SkillSystem.AtkOf(a));
}
int raw = Combat.Damage(cfg, a, d, false, rng, true, scale);
bool crit = Combat.LastCrit;
int dmg = SkillSystem.Deal(d, raw, a, HitKind.Attack);
var sys = SkillSystem.Current;
if (sys != null && pusher != null && pusher != a) sys.ApplyHitStatuses(pusher, d, false, HitKind.Indirect);
// 행동 유닛 자신의 공격 집계(o.Attacked · DamageDealt)에는 넣지 않는다 — 예전 밀린 공격과 같음(기록 = Notes)
Fx.Popup(d.Position, crit ? dmg + "!" : dmg.ToString(), crit ? new Color(1f, 0.7f, 0.2f) : Color.white);
int counter = 0;
if (d.IsAlive && a.IsAlive)
{
counter = Combat.CounterDamage(cfg, d, a, rng, true);
if (counter > 0)
{
if (d.View != null) d.View.PlayAttack();
counter = SkillSystem.Deal(a, counter, d, HitKind.Counter);
Fx.Popup(a.Position, counter.ToString(), new Color(1f, 0.45f, 0.45f));
}
}
battle.NotifyChanged();
o.Notes.Add("밀린 " + a.DisplayName + " → " + d.DisplayName + " 충돌 " + dmg + (counter > 0 ? " · 반격 " + counter : ""));
if (!a.IsAlive) yield break;
Vector2 n = d.Position - a.Position;
n = n.sqrMagnitude > 1e-6f ? n.normalized : inDir;
var side = new ActionOutcome();
Vector2 from = a.Position;
yield return Bounce(a, d, n, power, side, dmg, Mathf.Max(0, cfg.bounceChainMax), inDir);
o.Pushed.AddRange(side.Pushed);
o.Displaced.AddRange(side.Displaced);
o.Notes.AddRange(side.Notes);
if (a.IsAlive && (a.Position - from).sqrMagnitude > 1e-6f) o.Displaced.Add(new Displacement { Unit = a, From = from, To = a.Position });
}
}
}