ThreeKingdomsSlingshot/Assets/Scripts/Runtime/ActionResolver.cs

1513 lines
89 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;
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);
if (dist < 0.001f || !u.IsAlive) yield break;
Vector2 dir = delta / dist;
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++)
{
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);
}
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;
}
/// <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.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)) goto case UnitType.Cavalry;
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, 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))
{
// 조조 난세의 간웅: 자신은 밀리지 않고 탭한 방향으로 명중 적을 밀침(적·자동 = 슬링 방향)
Vector2 aimDir = n;
var sk = SkillSystem.Current;
if (sk != null)
yield return sk.WaitTap(u, SkillSystem.TapKind.Aim, 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; });
float force = 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)
{
// 반작용: 벽·유닛·장애물에 닿으면 정지 · 피해 없음 · 보는 방향은 유지(밀친 쪽을 본 채 물러남)
float back = Combat.FreeTravel(u, u.Position, -dir, recoil, true, true, first);
NoteForced(u, u.Position, u.Position - dir * back);
if (back > 0.01f)
{
Vector2 start = u.Position;
Vector2 end = battle.Board.ClampInside(start - dir * back, u.Radius);
yield return Fx.MoveAlong(u.transform, start, end, cfg.moveSpeed, null);
u.Position = end;
o.Path.Add(end);
}
}
while (!pushedDone) yield return null;
battle.NotifyChanged();
if (pushed && !enemy) yield return PushedAllyAttack(first, o, u);
// 목표점 명중 → 대기(견제) = 제거(PD 2026-11-10) · 새 스킬 기획(2026-11-10 #1112)에도 견제 없음
}
// ---------- 기병: 관통(제자리 복귀 없음 · 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;
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);
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;
if (aim)
{
var sk = SkillSystem.Current;
if (sk != null)
yield return sk.WaitTap(u, SkillSystem.TapKind.Return, u.Position, SkillMods.SlingMax(u), (o.SkillUsed != null ? o.SkillUsed.NameKo : "복귀") + " — 복귀할 곳을 탭", origin, w => dest = w);
}
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) 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>장료 요래: 관통으로 피해를 입힌 적을 출발 위치로 끌고 옴(가까운 적부터 출발점 · 뒤는 진행 방향으로 줄지음).</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 강하게 밀침 · 적 = 돌진 피해(반격 받음) · 자신은 튕기지 않음.</summary>
IEnumerator RampageRoutine(Unit u, Vector2 origin, Vector2 dir, ActionOutcome o)
{
var e0 = SkillMods.First(u, SkillKeys.Rampage, true);
float total = cfg.moveSpeed * (e0 != null ? e0.P : 1f);
float force = e0 != null ? e0.Get(1, 1f) : 1f;
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);
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 (n.sqrMagnitude < 0.5f || left <= 0.05f) break;
if (g != null)
{
var sk = SkillSystem.Current;
if (sk != null && sk.Ctx != null) sk.Ctx.HitTerrain = true;
}
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();
}
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);
// 조준 방향으로 사거리 안의 첫 적 — 있으면 제자리 사격 · 없으면(사거리 밖 · 방향이 맞지 않음) 쏘지 않고 목표점까지 이동(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); // 시전형(예약) 스킬 = 적이 없어도 조준한 자리로 발사(이동하지 않음)
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 (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 = Mathf.Clamp(Vector2.Dot(target - p.From, dir), 0.5f, range + u.Radius);
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): 튕겨나는 길의 첫 유닛(벽·장애물보다 앞) — 적 = 피해·반격 교환 후 다시 튕김 · 아군 = 밀기만(밀린 아군은 규칙 ⑤)
float h2;
Unit second = Combat.FirstUnitOnPathExcept(striker, striker.Position, bd, self, struck, out h2);
if (second != null && 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) yield return Bounce(striker, second, n2, rem2, o, imp2, chain - 1, bd);
}
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;
}
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);
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 (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)
{
if (ally == null || !ally.IsAlive) yield break;
if (Combat.TouchingOpponent(ally) == null) yield break;
Unit foe = Combat.TouchingOpponent(ally);
if (!ally.IsAlive || foe == null) yield break;
yield return Fx.Wait(0.1f);
Face(ally, foe.Position - ally.Position);
yield return PushedAttack(ally, foe, o, pusher);
}
/// <summary>
/// 밀린 유닛의 근접 공격 1회(반격 받음 · Notes 에 기록) — 장합 교변: 민 장합의 공격력 × p1 을 더함 · 장합 자신이 밀려 친 공격 = × p1 ·
/// 고순 함진영: 민 고순의 「명중 기절」이 이 공격에도(간접 명중). 원거리 병종도 근접 패널티를 받는다.
/// </summary>
IEnumerator PushedAttack(Unit a, Unit d, ActionOutcome o, Unit pusher = null)
{
if (a.View != null) a.View.PlayAttack();
yield return Fx.Lunge(a, d.Position);
float scale = SkillMods.Product(a, SkillKeys.SelfPushedMult, true);
if (pusher != null && pusher != a && pusher.Faction == a.Faction && 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 dmg = SkillSystem.Deal(d, Combat.Damage(cfg, a, d, false, rng, true, scale), a, HitKind.Attack);
var sys = SkillSystem.Current;
if (sys != null && pusher != null && pusher != a && pusher.Faction == a.Faction) sys.ApplyHitStatuses(pusher, d, false, HitKind.Indirect);
Fx.Popup(d.Position, dmg.ToString(), Color.white);
battle.NotifyChanged();
yield return Fx.Wait(0.2f);
int counter = 0;
if (d.IsAlive && a.IsAlive)
{
counter = Combat.CounterDamage(cfg, d, a, rng, false);
if (counter > 0)
{
if (d.View != null) d.View.PlayAttack();
yield return Fx.Lunge(d, a.Position);
counter = SkillSystem.Deal(a, counter, d, HitKind.Counter);
Fx.Popup(a.Position, counter.ToString(), new Color(1f, 0.45f, 0.45f));
battle.NotifyChanged();
yield return Fx.Wait(0.2f);
}
}
o.Notes.Add("밀린 " + a.DisplayName + " → " + d.DisplayName + " 공격 " + dmg + (counter > 0 ? " · 반격 " + counter : ""));
}
}
}