using System.Collections.Generic;
using UnityEngine;
namespace TKS
{
///
/// 게이지 조작(PD 2026-11-16 · FGT 「당겼다 놓기 · 반대로 가는 화살표가 어렵다」 → 뒤로 당기기 폐기):
/// 아군 유닛을 누른 채 유닛 밖으로(반지름 × aimStartRadiusRatio) 끌면 끄는 쪽으로 화살표가 뜨고(끈 거리는 방향만 정함), 그때부터 게이지가 차오른다
/// (병종별 unitStats.gaugeCycleSec · 가득 차면 0 부터 다시 = 순환형 · gauge_pingpong 효과 유닛 = 왕복형). 놓으면 그 방향으로 최대 거리 × 놓는 순간의 게이지만큼 이동·공격 ·
/// 게이지가 aimGaugeCritFrom 이상일 때 놓으면 그 행동의 공격 = 반드시 치명타(막대 끝 강조 구간) ·
/// 손가락을 유닛 원 안으로 되돌리면 화살표·게이지가 사라지고(다시 끌면 게이지는 0 부터) 놓아도 발사 없음 = 스킬 사용 가능(PD 2026-11-16 5차).
/// 유닛 탭(아군·적군) = 그 유닛의 사거리 표시(RangeIndicator) · 빈 곳 드래그 = 전장 스크롤 · 휠 = 줌 · 미니맵 탭 = 그 지점으로 이동.
/// 버튼 없음. 결과 화면에서는 탭으로 계속. 추가 이동만 남았을 때 빈 곳 탭 = 건너뛰기.
/// 궁병도 다른 병종과 같이 놓으면 바로 행동한다(조준 방향에 적이 없으면 목표점까지 이동 · PD 2026-11-04 2차 지시).
///
public class SlingshotInput : MonoBehaviour
{
static readonly Color TargetFreeColor = Color.white;
static readonly Color TargetHitColor = new Color(1f, 0.6f, 0.1f);
static readonly Color ShotLineColor = new Color(1f, 0.92f, 0.6f, 0.95f);
static readonly Color ShotLineFriendlyColor = new Color(1f, 0.2f, 0.2f, 0.95f);
static readonly Color SplashAreaColor = new Color(0.7f, 0.45f, 1f, 0.22f);
static readonly Color SplashAreaFriendlyColor = new Color(1f, 0.25f, 0.25f, 0.26f);
BattleManager battle;
Camera cam;
BattleHUD hud;
CameraController camCtrl;
RangeIndicator range;
/// 결과 화면 탭(= 계속) 을 건너뛸 자리인가(화면 좌표) — 결과 패널 「다시」 버튼 위(#1104).
public System.Func HoldResultTap;
/// 이 자리(화면 좌표) 누름은 전장 조작으로 보지 않는다(스킬 테스트 씬 패널 위 · 2026-11-09). 뗄 때까지 무시.
public System.Func BlockPress;
bool pressBlocked;
Unit selected;
bool dragging;
/// 누른 뒤 손가락(마우스)이 화면에서 TapPixels 이상 움직였는가 — 그 전에는 당김 아님(PD 2026-11-10 「한 번이라도 약간 움직여야 슬링샷 · 아니면 스킬 시전 가능 상태」 · 카메라가 움직여 손 아래 월드가 바뀌어도 당겨지지 않게).
bool aimArmed;
/// 선택 확대 중(PD 2026-11-11) · 확대 전 화면 세로 크기.
bool selectZoomed;
float preSelectHeight;
Vector2 pressScreen;
/// 조준 중(손가락이 유닛 밖 · 화살표가 떠 있음)인가 · 조준이 시작된 시각(Time.unscaledTime) — 게이지 = 그 뒤 지난 시간으로 계산.
bool aiming;
float aimStart;
/// 마지막으로 쏜 아군 · 직전 프레임의 전투 단계 — 행동이 끝나면 다음 아군을 자동으로 고르는 데 쓴다(FocusNext).
Unit lastActor;
BattlePhase lastPhase;
bool focusPending;
float gauge;
Transform gaugeRoot;
SpriteRenderer gaugeBack, gaugeZone, gaugeFill;
Color gaugeFillColor, gaugeCritFillColor;
bool panning;
bool emptyPress;
bool previewValid;
Vector2 lastScreen;
float panPixels;
Vector2 currentTarget;
LineRenderer aimLine;
LineRenderer pullLine;
LineRenderer shotLine; // 궁병·책사 투사체 경로(쏘는 위치 → 첫 피격 지점 · PD 2026-11-05 #1087 ⑥)
SpriteRenderer targetRing;
SpriteRenderer splashArea; // 책사 광역 원(중심 = 첫 피격 유닛 · #1087 ⑤)
SpriteRenderer teleportArea; // 변진(장합) 목표 지점 반경(PD #1093 B)
readonly List highlighted = new List();
/// 방향 결정 UI = IB GameTouchArrow 이식(고리 + 화살표 · PD 2026-11-10 「IB 와 같이 방향 결정 UI 등을 그대로 이식」) — 전에 쓰던 조준선 · 당김선 대신.
IbAimArrow ibArrow;
/// 슬링샷 진행 중 캐릭터 연출(IB 이식): 행동할 유닛 발밑 원 · 몸 둘레 빛 + 조준 중 모든 유닛 속성 방울.
IbUnitMarks marks;
/// 조준 중 상성 표시(적 머리 위 유리·불리 화살표 · 1-4 부터 · 개발 요청서 C5).
MatchupMarks matchup;
public IbUnitMarks Marks
{
get { return marks; }
}
public MatchupMarks Matchup
{
get { return matchup; }
}
public bool AimArrowVisible
{
get { return ibArrow != null && ibArrow.ArrowVisible; }
}
public Unit Selected
{
get { return selected; }
}
/// 조준 게이지(0~1 · 유닛을 누르고 있는 동안만 의미).
public float Gauge
{
get { return gauge; }
}
public bool GaugeVisible
{
get { return gaugeRoot != null && gaugeRoot.gameObject.activeSelf; }
}
///
/// 누른 뒤 elapsed 초가 지났을 때의 게이지(0~1): 한 번 차는 시간 cycleSec · 순환형 = 가득 차면 0 부터 다시 · 왕복형 = 가득 차면 다시 내려옴 ·
/// cycleSec ≤ 0 = 게이지 없음(항상 1).
///
public static float GaugeAt(float elapsed, float cycleSec, bool pingPong)
{
if (cycleSec <= 0f) return 1f;
float k = Mathf.Max(0f, elapsed) / cycleSec;
return pingPong ? Mathf.PingPong(k, 1f) : Mathf.Repeat(k, 1f);
}
///
/// 조준(화살표·게이지)이 켜져 있어야 하는가: 꺼져 있을 때 = 손가락이 유닛 반지름 × aimStartRadiusRatio 밖으로 나가면 켜짐 ·
/// 켜져 있을 때 = 손가락이 유닛 원 안으로 돌아오면 꺼짐(경계에서 깜빡이지 않게 켜는 거리와 끄는 거리가 다르다).
///
public bool AimActive(Unit u, Vector2 finger, bool aimingNow)
{
float d = Vector2.Distance(finger, u.Position);
float ratio = battle.Config.aimStartRadiusRatio;
return d >= u.Radius * (aimingNow ? Mathf.Min(1f, ratio) : ratio);
}
///
/// 게이지 조작의 목표점: 방향 = 유닛 → 손가락(끈 거리는 쓰지 않음) · 거리 = 최대 거리 × 게이지(최소 minDragDistance) · 전장 안으로.
/// 손가락이 유닛 한가운데 = 방향 없음(null).
///
public Vector2? AimPoint(Unit u, Vector2 finger, float gauge01)
{
Vector2 dir = finger - u.Position;
float mag = dir.magnitude;
if (mag < 1e-4f) return null;
float dist = Mathf.Max(battle.Config.minDragDistance, SkillMods.SlingMax(u) * Mathf.Clamp01(gauge01)); // 동남풍·적토마(PD #1093 B)
return battle.Board.ClampInside(u.Position + dir / mag * dist, u.Radius);
}
public bool ShotLineVisible
{
get { return shotLine != null && shotLine.enabled; }
}
public bool SplashVisible
{
get { return splashArea != null && splashArea.gameObject.activeSelf; }
}
/// 책사 광역 원의 지름(월드) = strategistSplashRadius × 2 · 중심 = SplashCenter.
public float SplashDiameter
{
get { return splashArea != null ? splashArea.transform.localScale.x : 0f; }
}
public Vector2 SplashCenter
{
get { return splashArea != null ? (Vector2)splashArea.transform.position : Vector2.zero; }
}
public RangeIndicator Range
{
get { return range; }
}
float TapPixels
{
get { return Mathf.Max(8f, Screen.height * 0.012f); }
}
public void Init(BattleManager b, Camera c, BattleHUD h, CameraController cc)
{
battle = b;
cam = c;
hud = h;
camCtrl = cc;
aimLine = MakeLine("AimLine", 0.08f, new Color(1f, 1f, 1f, 0.9f), 10);
pullLine = MakeLine("PullLine", 0.035f, new Color(1f, 1f, 1f, 0.35f), 9);
shotLine = MakeLine("ShotLine", 0.05f, ShotLineColor, 10);
targetRing = ProceduralSprites.NewSprite(transform, "TargetRing", ProceduralSprites.Ring, Color.white, 0.7f, 11);
targetRing.enabled = false;
splashArea = ProceduralSprites.NewSprite(transform, "SplashArea", ProceduralSprites.Circle, SplashAreaColor, 1f, -8);
splashArea.gameObject.SetActive(false);
teleportArea = ProceduralSprites.NewSprite(transform, "TeleportArea", ProceduralSprites.Circle, new Color(1f, 0.85f, 0.3f, 0.18f), 1f, -8);
teleportArea.gameObject.SetActive(false);
var rgo = new GameObject("RangeIndicator");
rgo.transform.SetParent(transform, false);
range = rgo.AddComponent();
range.Init(b.Config.archerRangeRatio);
var ago = new GameObject("IbAimArrow");
ago.transform.SetParent(transform, false);
ibArrow = ago.AddComponent();
ibArrow.Init(b.Board);
marks = ago.AddComponent();
matchup = ago.AddComponent();
// 조준 게이지 막대(바탕 · 끝의 치명타 구간 · 채움) — 크기·색 = 표 ib_ui.csv gauge_*
var ggo = new GameObject("AimGauge");
ggo.transform.SetParent(transform, false);
gaugeRoot = ggo.transform;
int gorder = Mathf.RoundToInt(IbUi.Num("gauge_order", 12f));
gaugeBack = ProceduralSprites.NewSprite(gaugeRoot, "Back", ProceduralSprites.Square, Color.black, 1f, gorder);
gaugeZone = ProceduralSprites.NewSprite(gaugeRoot, "CritZone", ProceduralSprites.Square, Color.red, 1f, gorder + 1);
gaugeFill = ProceduralSprites.NewSprite(gaugeRoot, "Fill", ProceduralSprites.Square, Color.yellow, 1f, gorder + 2);
ggo.SetActive(false);
}
///
/// 게이지 막대: 유닛을 누르고 있는 동안 유닛 오른쪽에 세로로 표시(아래 → 위로 참 · PD 2026-11-16 「체력 바와 겹쳐 보이지 않게 유닛 우측에 세로로」) ·
/// 위쪽 끝(aimGaugeCritFrom ~ 1)은 치명타 구간 색 · 게이지가 그 구간에 들어오면 채움 색도 바뀜(PD 2026-11-16 「게이지 끝 부분을 색상으로 강조」).
///
void RefreshGauge()
{
if (gaugeRoot == null) return;
bool on = dragging && aiming && selected != null && SkillMods.GaugeCycle(selected) > 0f; // 화살표가 떠 있을 때만
if (gaugeRoot.gameObject.activeSelf != on)
{
gaugeRoot.gameObject.SetActive(on);
if (on)
{
gaugeBack.color = IbUi.Col("gauge_back_color", new Color(0.06f, 0.06f, 0.06f, 0.8f));
gaugeZone.color = IbUi.Col("gauge_crit_zone_color", new Color(1f, 0.23f, 0.19f));
gaugeFillColor = IbUi.Col("gauge_fill_color", new Color(1f, 0.82f, 0.24f));
gaugeCritFillColor = IbUi.Col("gauge_crit_fill_color", new Color(1f, 0.42f, 0.24f));
}
}
if (!on) return;
float k = IbUi.Scale(selected);
float w = IbUi.Num("gauge_width", 0.3f) * k, h = IbUi.Num("gauge_height", 1.6f) * k, pad = IbUi.Num("gauge_pad", 0.04f) * k;
float x = selected.Position.x + selected.Radius + IbUi.Num("gauge_gap", 0.25f) * k + w * 0.5f; // 유닛 오른쪽 가장자리 밖
float bottom = selected.Position.y + IbUi.Num("gauge_bottom", -0.55f) * selected.Radius; // 막대 아래 끝 = 유닛 그림의 발 높이
gaugeRoot.position = new Vector3(x, bottom + h * 0.5f, 0f);
float inW = Mathf.Max(0f, w - pad * 2f), inH = Mathf.Max(0f, h - pad * 2f);
float critFrom = Mathf.Clamp01(battle.Config.aimGaugeCritFrom);
gaugeBack.transform.localScale = new Vector3(w, h, 1f);
gaugeZone.transform.localScale = new Vector3(inW, inH * (1f - critFrom), 1f);
gaugeZone.transform.localPosition = new Vector3(0f, inH * critFrom * 0.5f, 0f);
gaugeFill.transform.localScale = new Vector3(inW, inH * gauge, 1f);
gaugeFill.transform.localPosition = new Vector3(0f, -inH * 0.5f + inH * gauge * 0.5f, 0f);
gaugeFill.color = gauge >= critFrom ? gaugeCritFillColor : gaugeFillColor;
}
LineRenderer MakeLine(string name, float width, Color color, int order)
{
var go = new GameObject(name);
go.transform.SetParent(transform, false);
var lr = go.AddComponent();
lr.useWorldSpace = true;
lr.positionCount = 2;
lr.startWidth = width;
lr.endWidth = width;
lr.material = new Material(Shader.Find("Sprites/Default"));
lr.startColor = color;
lr.endColor = color;
lr.sortingOrder = order;
lr.numCapVertices = 4;
lr.enabled = false;
return lr;
}
Vector2 ScreenToWorld(Vector2 screen)
{
Vector3 p = screen;
p.z = -cam.transform.position.z;
return cam.ScreenToWorldPoint(p);
}
void Update()
{
if (battle == null || battle.Config == null) return;
// 학습 판 안내(카드 · 잠긴 강조)가 떠 있는 동안 = 전장 조작·결과 넘기기 없음(개발 요청서 C5 · TutorialDirector)
var guide = TutorialDirector.Current;
if (guide != null && guide.BlocksInput)
{
if (dragging) CancelAim();
dragging = aimArmed = aiming = panning = emptyPress = previewValid = false;
return;
}
var phase = battle.Phase;
if (phase != lastPhase)
{
if (focusPending && lastPhase == BattlePhase.Resolving && phase == BattlePhase.PlayerTurn) FocusNext(); // 쏜 행동이 끝남 → 다음 아군으로(즉시형 스킬 연출 뒤에는 옮기지 않는다)
if (phase != BattlePhase.Resolving) focusPending = false;
lastPhase = phase;
}
if (phase == BattlePhase.StageClear || phase == BattlePhase.Defeat)
{
if (Input.GetMouseButtonDown(0) && (HoldResultTap == null || !HoldResultTap(Input.mousePosition))) battle.ContinueAfterResult();
return;
}
Vector2 screen = Input.mousePosition;
if (Input.GetMouseButtonDown(0)) pressBlocked = BlockPress != null && BlockPress(screen);
if (pressBlocked)
{
if (Input.GetMouseButtonUp(0) || !Input.GetMouseButton(0)) pressBlocked = false;
return;
}
if (Input.GetMouseButtonDown(0)) OnPress(screen);
else if (Input.GetMouseButton(0))
{
if (dragging && !aimArmed && (screen - pressScreen).magnitude > TapPixels) aimArmed = true;
if (dragging) OnHold(ScreenToWorld(screen));
else if (panning) OnPan(screen);
}
if (Input.GetMouseButtonUp(0)) OnRelease(screen);
RefreshGauge();
// 조준 중(첫 손가락으로 당기는 중) 다른 손가락으로 스킬 버튼 탭 = 예약/취소(PD #1093 B)
if (dragging && hud != null && Input.touchCount > 1)
{
for (int i = 1; i < Input.touchCount; i++)
{
var t = Input.GetTouch(i);
if (t.phase == TouchPhase.Began && hud.TrySkillTap(t.position) && selected != null && previewValid) ShowAim(selected, currentTarget);
}
}
RefreshTeleportArea();
float wheel = Input.mouseScrollDelta.y;
// 패널(테스트 씬 영웅 목록 등) 위 휠 = 목록 스크롤만 · 카메라 확대 안 함(PD 2026-11-10 「유비를 선택할 때 화면이 줌인된 상태」)
if (Mathf.Abs(wheel) > 0.01f && camCtrl != null && (BlockPress == null || !BlockPress(screen)) && (guide == null || !guide.Locked)) camCtrl.Zoom(1f - wheel * 0.1f);
}
/// 당기던 중 조작이 막혔을 때(안내 카드) 조준 표시를 걷는다.
void CancelAim()
{
HidePreview();
if (ibArrow != null) ibArrow.End();
if (marks != null) marks.HideBubbles();
if (matchup != null) matchup.Hide();
if (selected != null && selected.View != null) selected.View.SetAiming(false);
if (gaugeRoot != null) gaugeRoot.gameObject.SetActive(false);
}
/// 변진 목표 지점 대기 중이면 반경 원 표시.
void RefreshTeleportArea()
{
var sys = battle.Skills;
var u = sys != null ? sys.PendingUnit : null;
bool on = u != null && u.IsAlive && sys.PendingRadius > 0f; // 변진 목표 · 맹장 복귀 지점(조조 방향 탭 = 반경 없음)
if (on)
{
float d = sys.PendingRadius * 2f;
Vector2 c = sys.PendingKind == SkillSystem.TapKind.Teleport ? u.Position : sys.PendingCenter;
teleportArea.transform.position = new Vector3(c.x, c.y, 0f);
teleportArea.transform.localScale = new Vector3(d, d, 1f);
}
if (teleportArea.gameObject.activeSelf != on) teleportArea.gameObject.SetActive(on);
}
public bool TeleportAreaVisible
{
get { return teleportArea != null && teleportArea.gameObject.activeSelf; }
}
void OnPress(Vector2 screen)
{
lastScreen = screen;
pressScreen = screen;
aimArmed = false;
panPixels = 0f;
dragging = false;
panning = false;
emptyPress = false;
previewValid = false;
// 잠금 안내(학습 판) = 가리킨 것(그 유닛 · 스킬 버튼)만 누를 수 있다
var guide = TutorialDirector.Current;
if (guide != null && guide.Locked && !guide.AllowPress(screen, battle.UnitNear(ScreenToWorld(screen), Faction.Player))) return;
// 스킬 버튼(HUD) 탭 = 예약/취소/즉시 발동 · 변진 대기 중 = 목표 지점 탭(PD #1093 B)
if (hud != null && hud.TrySkillTap(screen))
{
if (guide != null) guide.NotifySkillTap();
return;
}
string tpMsg;
if (battle.Skills != null && battle.Skills.TryTeleportTap(ScreenToWorld(screen), out tpMsg))
{
if (!string.IsNullOrEmpty(tpMsg)) battle.LastMessage = tpMsg;
return;
}
Vector2 mapWorld;
if (hud != null && camCtrl != null && hud.TryMinimapTap(screen, out mapWorld))
{
camCtrl.FocusOn(mapWorld);
return;
}
Vector2 w = ScreenToWorld(screen);
var u = battle.UnitNear(w, Faction.Player);
if (u == null) u = battle.UnitNear(w, null); // 적 유닛 터치 = 적의 사거리 표시
Select(u);
if (u != null && battle.CanAct(u))
{
dragging = true;
aiming = false; // 유닛 밖으로 끌어야 화살표·게이지 시작
gauge = 0f;
if (camCtrl != null) camCtrl.StopFollow(); // 턴 시작 초점 이동 중에 누르면 화면이 아래로 끌려가 당김으로 잡히던 문제(PD 2026-11-10)
if (u.View != null) u.View.SetAiming(true);
if (ibArrow != null) ibArrow.Begin(u); // IB Ready: 누른 순간 고리
if (marks != null) marks.ShowBubbles(battle.Units); // IB: 조준 중 모든 유닛 속성 방울
if (matchup != null) matchup.Show(battle, u); // 적 머리 위 상성(유리·불리)
}
else if (u == null)
{
panning = true;
emptyPress = true;
}
}
void OnPan(Vector2 screen)
{
Vector2 d = screen - lastScreen;
lastScreen = screen;
panPixels += d.magnitude;
if (panPixels > TapPixels && camCtrl != null)
{
camCtrl.PanBy(-d * camCtrl.WorldUnitsPerPixel);
}
}
///
/// 유닛을 누르고 있는 동안 매 프레임: 손가락이 유닛 밖으로 나가면 조준 시작(화살표 + 그때부터 게이지) · 끈 쪽으로 조준(끈 거리는 방향만 · 이동 거리 = 최대 거리 × 게이지) ·
/// 유닛 원 안으로 돌아오면 화살표·게이지를 걷는다(놓으면 발사 없음 = 스킬 사용 가능 · 다시 끌면 게이지는 0 부터).
///
void OnHold(Vector2 w)
{
if (selected == null) return;
bool was = aiming;
aiming = aimArmed && AimActive(selected, w, aiming);
var p = aiming ? AimPoint(selected, w, 0f) : null;
if (!p.HasValue)
{
aiming = false;
gauge = 0f;
if (was || previewValid)
{
HidePreview();
if (ibArrow != null) ibArrow.Aim(selected, Vector2.zero, 0f); // 고리만 남김
}
previewValid = false;
return;
}
if (!was) aimStart = Time.unscaledTime; // 화살표가 뜨는 순간부터 게이지가 차오른다
gauge = GaugeAt(Time.unscaledTime - aimStart, SkillMods.GaugeCycle(selected), SkillMods.GaugePingPong(selected));
p = AimPoint(selected, w, gauge);
currentTarget = p.Value;
var guide = TutorialDirector.Current;
if (guide != null) currentTarget = guide.SnapAim(selected, currentTarget); // 잠긴 끌기 안내 = 목표 방향 · 정해진 세기로 맞춤
previewValid = true;
if (selected.View != null) selected.View.SetFacing(currentTarget - selected.Position); // 조준하는 동안 쏠 방향을 봄(PD 2026-11-11)
ShowAim(selected, currentTarget);
}
void OnRelease(Vector2 screen)
{
if (dragging && selected != null) OnHold(ScreenToWorld(screen)); // 놓는 순간의 게이지·방향으로 확정
var guide = TutorialDirector.Current;
bool fire = dragging && aimArmed && selected != null && previewValid && battle.CanAct(selected);
if (fire && guide != null && !guide.AllowShot(selected, currentTarget)) fire = false; // 잠금 안내와 다른 발사 = 취소
if (fire)
{
var t = currentTarget;
var u = selected;
HidePreview();
if (ibArrow != null) ibArrow.End();
if (marks != null) marks.HideBubbles();
if (matchup != null) matchup.Hide();
if (u.View != null) u.View.SetAiming(false);
bool gaugeCrit = SkillMods.GaugeCycle(u) > 0f && gauge >= battle.Config.aimGaugeCritFrom; // 게이지 끝 구간에서 놓음 = 반드시 치명타
Select(null);
lastActor = u;
focusPending = battle.RequestPlayerAction(u, t, gaugeCrit);
}
else if (emptyPress && panPixels <= TapPixels)
{
battle.OnEmptyTap();
}
else
{
HidePreview();
if (ibArrow != null) ibArrow.End();
if (marks != null) marks.HideBubbles();
if (matchup != null) matchup.Hide();
if (dragging && selected != null && selected.View != null) selected.View.SetAiming(false);
if (dragging && guide != null) guide.OnAimCancelled();
}
dragging = false;
aimArmed = false;
aiming = false;
panning = false;
emptyPress = false;
previewValid = false;
}
///
/// 아군 유닛 선택 = 그 유닛을 화면에서 제자리에 둔 채 약간 확대(BalanceConfig.selectZoomRatio · PD 2026-11-11 「캐릭터 선택 상태가 되면 약간 줌인」) ·
/// 해제(null · 적 선택) = 확대 전 크기로 · 당김은 화면에서 손가락이 움직여야 시작하므로 확대 중 누르고 있어도 당겨지지 않음.
///
void SelectZoom(Unit u)
{
if (camCtrl == null || battle == null || battle.Config == null) return;
float ratio = battle.Config.selectZoomRatio;
if (u != null && u.Faction == Faction.Player && ratio > 0f && ratio < 0.999f)
{
if (!selectZoomed)
{
preSelectHeight = camCtrl.ViewHeight;
selectZoomed = true;
}
camCtrl.ZoomTo(preSelectHeight * ratio, u.Position);
}
else if (selectZoomed)
{
selectZoomed = false;
camCtrl.ZoomTo(preSelectHeight, camCtrl.transform.position);
}
}
/// 유닛 선택(아군·적군 · null = 해제): 선택 링 + HUD 정보 + 사거리 표시(궁병은 도넛 · 범위 안 적 유무로 색).
public void Select(Unit u)
{
if (selected != null && selected.View != null)
{
selected.View.SetSelected(false);
selected.View.SetAiming(false);
}
selected = u;
if (u != null && u.View != null) u.View.SetSelected(true);
SelectZoom(u);
if (hud != null) hud.SetSelected(u);
if (range != null)
{
range.Show(u);
if (u != null && UnitTypeInfo.IsRanged(u.Type)) range.SetArcherReachable(battle.AnyEnemyWithinArcherReach(u));
}
if (marks != null) marks.ShowTurn(u != null && u.Faction == Faction.Player && battle.CanAct(u) ? u : null); // IB ShowUserTurnMark
var guide = TutorialDirector.Current;
if (guide != null) guide.OnSelect(u); // 학습 판 안내(unit_select · 누름 안내 닫기 · 조준 안내)
}
///
/// 플레이어 조준 표시 = 방향 화살표만(PD 2026-11-16 「선택된 유닛에게 보여지는 주황색 원과 예상 경로 표시는 모두 제거」) —
/// 맞을 유닛의 주황 강조 · 예상 궤적 · 화살 경로선 · 광역 원은 손 조작에서는 보이지 않는다(ShowPreview = 자동 플레이 캡처·테스트가 부르는 미리 보기로만 남음).
///
void ShowAim(Unit u, Vector2 target)
{
if (ibArrow != null) ibArrow.Aim(u, target - u.Position, (target - u.Position).magnitude / Mathf.Max(0.001f, SkillMods.SlingMax(u)));
}
///
/// 행동이 끝나 다시 아군 차례가 되면 다음에 행동할 아군을 고르고 화면을 그 유닛으로 옮긴다(PD 2026-11-16 「선택한 유닛의 행동이 종료되면 다음 행동할 아군 유닛을 자동으로 포커싱」) —
/// 방금 유닛이 또 행동할 수 있으면(추가 이동 · 재행동) 그 유닛 · 아니면 편성 순서로 그다음 유닛. 잠금 안내(학습 판) 중에는 안내가 가리키는 유닛을 따른다.
///
void FocusNext()
{
var guide = TutorialDirector.Current;
if (guide != null && guide.Locked) return;
Unit next = null;
if (lastActor != null && battle.CanAct(lastActor)) next = lastActor;
else
{
var allies = new List(battle.AliveUnits(Faction.Player));
int start = allies.IndexOf(lastActor);
for (int i = 1; i <= allies.Count && next == null; i++)
{
var c = allies[(start + i) % allies.Count];
if (battle.CanAct(c)) next = c;
}
}
if (next == null) return;
if (camCtrl != null) camCtrl.FocusOn(next.Position);
Select(next);
}
/// 조준 미리 보기(자동 플레이 캡처·테스트가 부른다 · 손 조작은 ShowAim). 반환 = 공격 예정 적 수.
public int ShowPreview(Unit u, Vector2 target, Vector2? pointer)
{
Vector2 aim = target;
target = battle.Resolver.ReachPoint(u, target); // 늪·고지 = 실제 정지점(PD #1097)
if (ibArrow != null)
{
// IB 방향 결정 UI: 화살표 = 쏠 방향 · 길이 = 이동할 거리 / 최대 거리(= 게이지 · PD 2026-11-16) — 조준선 · 당김선 대신(PD 2026-11-10)
ibArrow.Aim(u, aim - u.Position, (aim - u.Position).magnitude / Mathf.Max(0.001f, SkillMods.SlingMax(u)));
aimLine.enabled = false;
pullLine.enabled = false;
}
else
{
aimLine.enabled = true;
aimLine.SetPosition(0, new Vector3(u.Position.x, u.Position.y, 0f));
aimLine.SetPosition(1, new Vector3(target.x, target.y, 0f));
pullLine.enabled = pointer.HasValue;
if (pointer.HasValue)
{
pullLine.SetPosition(0, new Vector3(u.Position.x, u.Position.y, 0f));
pullLine.SetPosition(1, new Vector3(pointer.Value.x, pointer.Value.y, 0f));
}
}
targetRing.enabled = false; // 목표 지점 흰 고리 = 끔(PD 2026-11-11 「슬링샷 화살표에 보이는 흰색 원형 제거」 · 착지 위치는 화살표 끝)
targetRing.transform.position = new Vector3(target.x, target.y, 0f);
bool moveOnly = u.BonusMoveAvailable;
var finalHit = moveOnly ? null : Combat.EnemyAtPoint(u, target, battle.Config.finalHitTolerance);
targetRing.color = finalHit != null ? TargetHitColor : TargetFreeColor;
targetRing.transform.localScale = finalHit != null ? new Vector3(0.9f, 0.9f, 1f) : new Vector3(0.7f, 0.7f, 1f);
ClearHighlights();
var shot = battle.Resolver.PreviewShot(u, aim, moveOnly);
var gl = battle.Gimmicks;
if (gl != null) gl.Preview.Show(u, aim, moveOnly, shot); // 예상 궤적(튕김·밀림·연쇄·반작용) · 기믹 반응 · 지대 띠(PD #1097 · #1098)
if (shot != null)
{
return ShowShot(u, shot);
}
HideShot();
foreach (var e in battle.Resolver.PredictTargets(u, aim, moveOnly)) Highlight(e, false);
return highlighted.Count;
}
///
/// 궁병·책사 조준(PD 2026-11-05 #1087 ⑤⑥): 화살 경로선(쏘는 위치 → 첫 피격 지점) + 첫 피격 유닛 강조(같은 편이면 붉게)
/// · 책사 = 맞을 자리 광역 원 + 휩쓸릴 유닛 강조(같은 편 붉게). 반환 = 맞을 상대 유닛 수.
///
int ShowShot(Unit u, ActionResolver.ShotPlan shot)
{
if (!shot.Fires)
{
HideShot();
return 0;
}
bool friendlyCenter = shot.Hit != null && shot.Hit.Faction == u.Faction;
shotLine.enabled = true;
shotLine.startColor = shotLine.endColor = friendlyCenter ? ShotLineFriendlyColor : ShotLineColor;
shotLine.SetPosition(0, new Vector3(shot.From.x, shot.From.y, 0f));
shotLine.SetPosition(1, new Vector3(shot.To.x, shot.To.y, 0f));
int foes = 0;
if (shot.Hit != null)
{
Highlight(shot.Hit, friendlyCenter);
if (!friendlyCenter) foes++;
}
foreach (var t in shot.Pierced) // 레이저 = 경로 위 적 전원(첫 적은 위에서 셈)
{
if (t == shot.Hit) continue;
Highlight(t, false);
foes++;
}
bool splash = u.Type == UnitType.Strategist && shot.HasSplash; // 덤불·수레에 막혀도 그 자리 광역(PD #1097)
if (splash)
{
bool anyFriendly = friendlyCenter;
foreach (var s in shot.Splash)
{
bool friendly = s.Faction == u.Faction;
Highlight(s, friendly);
if (friendly) anyFriendly = true;
else foes++;
}
float d = shot.SplashRadius * 2f; // 화공 = 반경 ×(PD #1093 B) · 안개 중심 = ×p1
splashArea.transform.position = new Vector3(shot.SplashCenter.x, shot.SplashCenter.y, 0f);
splashArea.transform.localScale = new Vector3(d, d, 1f);
splashArea.color = anyFriendly ? SplashAreaFriendlyColor : SplashAreaColor;
}
if (splashArea.gameObject.activeSelf != splash) splashArea.gameObject.SetActive(splash);
return foes;
}
void HideShot()
{
shotLine.enabled = false;
splashArea.gameObject.SetActive(false);
}
void Highlight(Unit e, bool friendly)
{
if (e == null || highlighted.Contains(e)) return;
if (e.View != null) e.View.SetHighlight(true, friendly);
highlighted.Add(e);
}
public void HidePreview()
{
aimLine.enabled = false;
pullLine.enabled = false;
targetRing.enabled = false;
HideShot();
ClearHighlights();
if (battle != null && battle.Gimmicks != null) battle.Gimmicks.Preview.Hide();
}
void ClearHighlights()
{
foreach (var h in highlighted)
{
if (h != null && h.View != null) h.View.SetHighlight(false);
}
highlighted.Clear();
}
}
}