ThreeKingdomsSlingshot/Assets/Scripts/Runtime/Scenario/ScenarioProps.cs

259 lines
11 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.Generic;
using System.Globalization;
using UnityEngine;
namespace TKS
{
/// <summary>
/// 시나리오 판 꾸밈(2026-11-18 PD 「연의 전기 1 은 주점 내부처럼 꾸미고 술 테이블(맵 지형 오브젝트) 같은 것을 배치한 상태에서 진행 · 시나리오 상황에 맞는 연출 · 배경 · 소품 구성」).
/// 표 = Resources/Scenario/scenario_props.csv(SOT = 기획 tables/ · utf-8-sig): s_battle_id,n_chapter,n_stage,s_prop_id,s_art,f_x,f_y,f_w,b_block,f_block_r,Memo
/// · s_battle_id 있음 = 연의 편(n_stage = 막) · 빈칸 = 출정 판(n_chapter, n_stage)
/// · s_prop_id `_bg` = 그 판 바닥 그림(Resources/Board/&lt;s_art&gt; · 연출 bg 명령 없이도 전투 내내) · 그 밖 = 소품 그림(Resources/Scenario/Props/&lt;s_art&gt;) 을 (f_x, f_y) 에 폭 f_w(칸)로 ·
/// b_block 1 = 반지름 f_block_r 의 벽(BoardWall · 유닛이 부딪혀 튕김 · 적 AI 예측도 같은 판정).
/// 전투 시작(BattleManager.Begin)마다 앞 판 소품을 치우고 새로 놓는다 · 연무장(Mode) 전투 제외 · 값은 모두 표(C45).
/// </summary>
public static class ScenarioProps
{
public class Row
{
public int chapter, stage;
public string battle, id, art;
public float x, y, w, blockR;
public bool block;
}
static List<Row> rows;
static GameObject rootGo;
public static readonly List<string> Errors = new List<string>();
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStatics()
{
rows = null;
rootGo = null;
StageBg = "";
}
static void Load()
{
if (rows != null) return;
rows = new List<Row>();
Errors.Clear();
var ta = Resources.Load<TextAsset>(ScenarioData.Root + "scenario_props");
if (ta == null) return;
foreach (var r in StageTable.ReadCsv(ta.text, "scenario_props.csv", Errors))
{
var row = new Row
{
battle = S(r, "s_battle_id"),
chapter = I(r, "n_chapter"),
stage = I(r, "n_stage"),
id = S(r, "s_prop_id"),
art = S(r, "s_art"),
x = F(r, "f_x"),
y = F(r, "f_y"),
w = F(r, "f_w"),
block = I(r, "b_block") == 1,
blockR = F(r, "f_block_r"),
};
if (row.art.Length == 0) Errors.Add("scenario_props.csv 행 " + S(r, "#") + ": s_art 빈칸");
rows.Add(row);
}
foreach (var e in Errors) Debug.LogError("[TKS] 시나리오 소품 표 " + e);
}
public static IList<Row> All
{
get
{
Load();
return rows;
}
}
static string S(Dictionary<string, string> r, string k)
{
string v;
return r.TryGetValue(k, out v) ? v : "";
}
static int I(Dictionary<string, string> r, string k)
{
int v;
return int.TryParse(S(r, k), NumberStyles.Integer, CultureInfo.InvariantCulture, out v) ? v : 0;
}
static float F(Dictionary<string, string> r, string k)
{
float v;
return float.TryParse(S(r, k), NumberStyles.Float, CultureInfo.InvariantCulture, out v) ? v : 0f;
}
/// <summary>앞 판 소품 치우기 → 이 판 바닥 · 소품 놓기(그림이 없으면 그 줄만 건너뜀 · 경고 1줄).</summary>
public static void Apply(BattleManager bm, BalanceConfig.StageDef stage)
{
Clear();
// 켜짐 = 시나리오 연출과 같은 규칙(메모리 저장 = 자동 테스트 · 검증 캡처에서는 꺼짐 — 1-1 을 일반 전투로 쓰는 기존 테스트 보호)
if (bm == null || stage == null || bm.Board == null || !ScenarioEvent.Enabled) return;
string bid;
int ch, st;
if (!ScenarioEvent.KeyOf(bm, stage, out bid, out ch, out st)) return; // 연의 편 = (편 id, 막) · 출정 = s_battle_id 빈 줄(2026-11-18 PD 「연의 전기와 출정은 별개」)
Load();
foreach (var r in rows)
{
if (r.battle != bid) continue;
if (bid.Length > 0 ? r.stage != st : (r.chapter != ch || r.stage != st)) continue;
if (r.id == "_bg")
{
bm.Board.SetEventArt(r.art);
StageBg = r.art;
continue;
}
var sp = Resources.Load<Sprite>(ScenarioData.Root + "Props/" + r.art);
if (sp == null)
{
Debug.LogWarning("[TKS] 시나리오 소품 그림 없음: Scenario/Props/" + r.art);
continue;
}
if (rootGo == null)
{
rootGo = new GameObject("ScenarioProps");
rootGo.transform.SetParent(bm.Board.transform, false);
}
var go = new GameObject("Prop_" + r.id);
go.transform.SetParent(rootGo.transform, false);
go.transform.position = new Vector3(r.x, r.y, 0f);
var sr = go.AddComponent<SpriteRenderer>();
sr.sprite = sp;
sr.sortingOrder = -1; // 유닛(0) 아래 · 바닥(−20 · 이벤트 바닥 −19) 위
float s = sp.bounds.size.x > 0.001f ? r.w / sp.bounds.size.x : 1f;
go.transform.localScale = new Vector3(s, s, 1f);
if (r.block && r.blockR > 0.01f)
{
var col = go.AddComponent<CircleCollider2D>();
col.radius = r.blockR / s; // 로컬 반지름(그림 배율로 나눔)
go.AddComponent<BoardWall>();
var pb = go.AddComponent<PropBody>();
pb.Init(bm, r, sr, Resources.Load<Sprite>(ScenarioData.Root + "Props/" + r.art + "_broken"));
}
}
}
/// <summary>이 판의 바닥 그림(_bg 행 · 없으면 "") — 연출 bg 명령이 다른 장소로 바꾸면 이 판 소품을 치운다(ScenarioEvent).</summary>
public static string StageBg = "";
public static void Clear()
{
StageBg = "";
if (rootGo != null) Object.Destroy(rootGo);
rootGo = null;
}
/// <summary>지금 놓인 소품 수(테스트·캡처 확인용).</summary>
public static int Count
{
get { return rootGo != null ? rootGo.transform.childCount : 0; }
}
}
}
namespace TKS
{
/// <summary>
/// 막히는 소품 = 유닛이 움직이다 닿으면 부서짐(2026-11-18 PD 「소품은 유닛과 부딪힐 경우 부서지게」).
/// 판정 = 전투 행동 중(Resolving · 적 턴)에만 · 이번 프레임에 움직인 유닛이 (유닛 반지름 + 소품 반지름 + prop_break_contact) 안 → 부서짐
/// (연출 중 걸음 · 가만히 붙어 선 유닛은 부수지 않음 · 가상 실행 제외). 부서지면 벽을 바로 치우고 「그림_broken」 이 있으면 그 그림으로 남기고 없으면 튀어 오르며 사라진다.
/// 값 = scenario_event_config.csv prop_break_*(C45).
/// </summary>
public class PropBody : MonoBehaviour
{
BattleManager bm;
ScenarioProps.Row row;
SpriteRenderer sr;
Sprite broken;
bool done;
readonly System.Collections.Generic.Dictionary<Unit, Vector2> last = new System.Collections.Generic.Dictionary<Unit, Vector2>();
public bool Broken
{
get { return done; }
}
public void Init(BattleManager battle, ScenarioProps.Row r, SpriteRenderer renderer, Sprite brokenArt)
{
bm = battle;
row = r;
sr = renderer;
broken = brokenArt;
}
void Update()
{
if (done || bm == null || Sim.Active) return;
bool acting = bm.Phase == BattlePhase.Resolving || bm.Phase == BattlePhase.EnemyTurn;
float contact = ScenarioData.EvCfg("prop_break_contact");
Vector2 me = transform.position;
foreach (var f in new[] { Faction.Player, Faction.Enemy })
foreach (var u in bm.AliveUnits(f))
{
Vector2 p = u.Position, prev;
bool moved = last.TryGetValue(u, out prev) && (p - prev).sqrMagnitude > 0.0001f;
last[u] = p;
if (acting && moved && Vector2.Distance(p, me) <= u.Radius + row.blockR + contact)
{
Break();
return;
}
}
}
/// <summary>부숨(테스트도 부른다).</summary>
public void Break()
{
if (done) return;
done = true;
foreach (var c in GetComponents<Collider2D>()) Destroy(c);
var wall = GetComponent<BoardWall>();
if (wall != null) Destroy(wall);
var cc = FindFirstObjectByType<CameraController>();
if (cc != null) cc.Shake(ScenarioData.EvCfg("prop_break_shake_sec"), ScenarioData.EvCfg("prop_break_shake"));
StartCoroutine(Pop());
}
System.Collections.IEnumerator Pop()
{
float dur = Mathf.Max(0.01f, ScenarioData.EvCfg("prop_break_sec"));
Vector3 s0 = transform.localScale;
float peak = ScenarioData.EvCfg("prop_break_pop");
if (broken != null)
{
// 부서진 그림으로 바꾸고 바닥에 남김(같은 폭)
float w0 = sr.bounds.size.x;
sr.sprite = broken;
float k = broken.bounds.size.x > 0.001f ? w0 / sr.bounds.size.x : 1f;
s0 = s0 * k;
for (float t = 0f; t < dur; t += Time.deltaTime)
{
float q = t / dur;
transform.localScale = s0 * Mathf.Lerp(peak, 1f, q);
yield return null;
}
transform.localScale = s0;
sr.sortingOrder = -2;
yield break;
}
Color c0 = sr.color;
for (float t = 0f; t < dur; t += Time.deltaTime)
{
float q = t / dur;
transform.localScale = s0 * Mathf.Lerp(1f, peak, q);
transform.localRotation = Quaternion.Euler(0f, 0f, 25f * q);
sr.color = new Color(c0.r, c0.g, c0.b, c0.a * (1f - q));
yield return null;
}
gameObject.SetActive(false);
}
}
}