ThreeKingdomsSlingshot/Assets/Scripts/Runtime/CameraController.cs

258 lines
10 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 UnityEngine;
namespace TKS
{
/// <summary>
/// 넓은 전장용 카메라: 화면보다 큰 전장을 빈 곳 드래그로 스크롤 · 휠로 줌 · 행동 중인 유닛 자동 추적 · 전장 밖으로 못 나가게 고정.
/// </summary>
public class CameraController : MonoBehaviour
{
public Board Board;
public float ViewHeight = 18f;
public float MinViewHeight = 10f;
public float MaxViewHeight = 36f;
public float Margin = 1f;
[Tooltip("위쪽 HUD(스테이지·턴 글자) 밑에 유닛이 깔리지 않도록 전장 위 끝을 더 내려 볼 수 있는 여유")]
public float TopMargin = 2.6f;
[Tooltip("아래쪽 HUD(안내·유닛 정보) 여유")]
public float BottomMargin = 2.2f;
[Tooltip("위 · 아래 HUD 가 덮는 화면 높이(기준 1080×1920 px · 전투 HUD 표 cam_hud) — 확대 배율과 무관하게 전장 끝을 HUD 밖까지 내려 볼 여유(위 여유와 큰 쪽)")]
public float TopHudRefPx;
public float BottomHudRefPx;
public float FollowSpeed = 7f;
Camera cam;
Vector2? focusTarget;
Transform followTarget;
public Camera Cam
{
get
{
if (cam == null) cam = GetComponent<Camera>();
return cam;
}
}
public void Init(Board board, float viewHeight, float minViewHeight, float maxViewHeight)
{
Board = board;
MinViewHeight = Mathf.Max(1f, minViewHeight);
MaxViewHeight = Mathf.Max(MinViewHeight, maxViewHeight);
ViewHeight = Mathf.Clamp(viewHeight, MinViewHeight, MaxViewHeight);
Cam.orthographicSize = ViewHeight * 0.5f;
SetPosition(transform.position);
}
/// <summary>화면 1 픽셀이 월드 몇 단위인가(드래그 스크롤 환산).</summary>
public float WorldUnitsPerPixel
{
get { return Cam.orthographicSize * 2f / Mathf.Max(1, Cam.pixelHeight); }
}
public Rect ViewRect
{
get
{
float halfH = Cam.orthographicSize;
float halfW = halfH * Cam.aspect;
Vector2 c = transform.position;
return new Rect(c.x - halfW, c.y - halfH, halfW * 2f, halfH * 2f);
}
}
public void PanBy(Vector2 worldDelta)
{
focusTarget = null;
followTarget = null;
SetPosition((Vector2)transform.position + worldDelta);
}
public void FocusOn(Vector2 worldPos)
{
followTarget = null;
focusTarget = worldPos;
}
public void SnapTo(Vector2 worldPos)
{
followTarget = null;
focusTarget = null;
SetPosition(worldPos);
}
public void Follow(Transform t)
{
focusTarget = null;
followTarget = t;
}
public void StopFollow()
{
followTarget = null;
focusTarget = null;
}
public void Zoom(float factor)
{
zoomGoal = null;
SetViewHeight(ViewHeight * factor);
}
// 부드러운 확대(PD 2026-11-11 「캐릭터 선택 상태가 되면 약간 줌인」): 기준점(선택 유닛)이 화면에서 같은 자리에 머물도록 확대하며 카메라를 옮김
float? zoomGoal;
Vector2 zoomAnchor;
const float ZoomSpeed = 10f;
/// <summary>height 로 부드럽게 확대·축소 · anchorWorld = 화면에서 제자리에 남을 점(선택 유닛 · 화면 가운데).</summary>
public void ZoomTo(float height, Vector2 anchorWorld)
{
zoomGoal = Mathf.Clamp(height, MinViewHeight, MaxViewHeight);
zoomAnchor = anchorWorld;
}
/// <summary>지금 가고 있는 화면 높이(부드러운 확대 중이면 그 목표 · 아니면 지금 높이).</summary>
public float TargetHeight
{
get { return zoomGoal ?? ViewHeight; }
}
void StepZoom()
{
if (!zoomGoal.HasValue) return;
float goal = zoomGoal.Value;
float h = Mathf.Lerp(ViewHeight, goal, 1f - Mathf.Exp(-ZoomSpeed * Time.unscaledDeltaTime));
if (Mathf.Abs(h - goal) < 0.01f)
{
h = goal;
zoomGoal = null;
}
Vector2 cam = transform.position;
float s = h / Mathf.Max(0.01f, ViewHeight);
ViewHeight = h;
Cam.orthographicSize = h * 0.5f;
SetPosition(zoomAnchor - (zoomAnchor - cam) * s);
}
public void SetViewHeight(float height)
{
zoomGoal = null;
ViewHeight = Mathf.Clamp(height, MinViewHeight, MaxViewHeight);
Cam.orthographicSize = ViewHeight * 0.5f;
SetPosition(transform.position);
}
// 화면 흔들림(타격감 · PD 2026-11-10 「타격감을 위한 화면 효과(화면 흔들림 등)도 IB 를 참고해서」) — 추적·스크롤 위치(기준)에 매 프레임 흔들림만 더하고
// 다음 프레임 처음에 빼서 기준 위치를 흔들지 않는다. 값 = 표(Resources/Skills/hit_feel.csv · HitFeel).
Vector2 shakeApplied;
float shakeTime;
float shakeDuration;
float shakeMagnitude;
/// <summary>흔들기 시작(진행 중이면 더 센 쪽을 남김) · duration 초 · magnitude = 최대 흔들림(월드 단위) · 끝으로 갈수록 약해짐.</summary>
public void Shake(float duration, float magnitude)
{
if (duration <= 0f || magnitude <= 0f) return;
float remain = shakeDuration > 0f ? shakeMagnitude * Mathf.Clamp01(1f - shakeTime / shakeDuration) : 0f;
if (magnitude < remain) return;
shakeDuration = duration;
shakeMagnitude = magnitude;
shakeTime = 0f;
}
public bool Shaking
{
get { return shakeDuration > 0f && shakeTime < shakeDuration; }
}
void LateUpdate()
{
if (shakeApplied != Vector2.zero) // 지난 프레임 흔들림 빼기(기준 위치 복원)
{
transform.position -= (Vector3)shakeApplied;
shakeApplied = Vector2.zero;
}
StepZoom();
Follow();
StickBottom();
if (Shaking)
{
shakeTime += Time.unscaledDeltaTime;
float k = Mathf.Clamp01(1f - shakeTime / shakeDuration);
shakeApplied = Random.insideUnitCircle * (shakeMagnitude * k);
transform.position += (Vector3)shakeApplied;
}
}
void Follow()
{
Vector2? goal = null;
if (followTarget != null && followTarget.gameObject.activeInHierarchy) goal = (Vector2)followTarget.position;
else if (focusTarget.HasValue) goal = focusTarget;
if (!goal.HasValue) return;
Vector2 target = Clamp(goal.Value);
Vector2 cur = transform.position;
float k = 1f - Mathf.Exp(-FollowSpeed * Time.deltaTime);
Vector2 next = Vector2.Lerp(cur, target, k);
SetPosition(next);
if (focusTarget.HasValue && Vector2.Distance(next, target) < 0.02f) focusTarget = null;
}
void SetPosition(Vector2 p)
{
p = Clamp(p);
transform.position = new Vector3(p.x, p.y, -10f);
}
/// <summary>HUD 높이(기준 px · UI 캔버스 = 1080×1920 · Expand 맞춤) → 지금 확대에서 월드 높이.</summary>
float HudWorld(float refPx, float halfH)
{
if (refPx <= 0f) return 0f;
float w = Mathf.Max(1, Cam.pixelWidth), h = Mathf.Max(1, Cam.pixelHeight);
float scale = UiLayer.ScaleFactor(w, h); // CanvasScaler 와 같은 식(UiLayer.Root · 2026-11-26 Expand)
return refPx * scale / h * halfH * 2f;
}
/// <summary>
/// 카메라 중심이 내려갈 수 있는 아래 한계 — 아래 HUD 높이(BottomHudRefPx · 전투 HUD 지휘 탁자 = 낮은 띠 120 / 선택 280 · 매 프레임)가 있으면 그만큼만 전장 밖을 보임
/// (전장 아래끝 = 탁자 윗변 · 빈 검은 띠 0 · 2026-11-21 QA r1 F2) · 없으면 BottomMargin.
/// </summary>
float MinY(float halfH)
{
float m = BottomHudRefPx > 0f ? HudWorld(BottomHudRefPx, halfH) + UiSafeArea.Bottom * halfH * 2f : BottomMargin; // + 제스처 바(HUD 가 그만큼 올라감 · 2026-11-26)
return Board.Rect.yMin - m + halfH;
}
// 아래 끝 붙음(2026-11-21 QA r1 F1): 카메라가 아래 한계에 있을 때 HUD 높이가 바뀌면(영웅 선택 = 탁자가 올라옴) 한계를 따라감 →
// 전장 아래끝이 늘 탁자 윗변에 붙어 아래 줄 유닛이 탁자 밑에 깔리지 않고, 탁자가 내려가면 빈 띠 없이 다시 붙음
bool atBottom;
void StickBottom()
{
if (Board == null || BottomHudRefPx <= 0f) return;
float halfH = Cam.orthographicSize;
float minY = MinY(halfH);
Vector2 p = transform.position;
bool free = followTarget == null && !focusTarget.HasValue;
if (free && (atBottom || p.y < minY) && Mathf.Abs(p.y - minY) > 0.0001f) SetPosition(new Vector2(p.x, minY)); // 붙어 있었으면 따라감 · 한계 밑이면 올림
atBottom = transform.position.y <= MinY(halfH) + 0.02f;
}
public Vector2 Clamp(Vector2 p)
{
if (Board == null) return p;
float halfH = Cam.orthographicSize;
float halfW = halfH * Cam.aspect;
var r = Board.Rect;
float minX = r.xMin - Margin + halfW;
float maxX = r.xMax + Margin - halfW;
float minY = MinY(halfH);
float maxY = r.yMax + Mathf.Max(TopMargin, HudWorld(TopHudRefPx, halfH) + UiSafeArea.Top * halfH * 2f) - halfH; // + 노치(위 띠가 그만큼 내려감 · 2026-11-26)
p.x = minX > maxX ? 0f : Mathf.Clamp(p.x, minX, maxX);
p.y = minY > maxY ? 0f : Mathf.Clamp(p.y, minY, maxY);
return p;
}
}
}