Files
2026-11-25 21:35:17 +08:00

239 lines
10 KiB
C#

using System.Collections.Generic;
using UnityEngine;
// 模擬 AI 視覺外掛的「眼睛」
// 1. 自動配置 : 每一幀取樣一次 (固定 60 FPS,不因每個人的螢幕而不同) ; 自由 / 測試模式 : 依螢幕刷新率取樣
// 2. 敵人被擋住 25% 以上就偵測不到 (視覺辨識的特性) ; 比例依身體各部位的面積加權 : 頭 15%、身體 45%、腿 40%
// 3. 結果延遲一段時間才給輔助用 (擷取 → 辨識 → 輸出的鏈路延遲)
// 真值 (Truth) 和外掛實際拿到的結果 (Output) 都保留,之後記錄器兩個都存
public class EnemyPerceptor : MonoBehaviour
{
public struct Detection
{
public bool detected; // 有沒有偵測到
public float visibleRatio; // 沒被擋住的比例 0~1
public Vector2 angleError; // 準心到胸口的角度 (度) : x = 往右,y = 往上
public Vector2 screenOffset; // 胸口相對畫面中心的像素座標 : x 往右,y 往上
public float captureTime; // 擷取畫面的時間
public float delay; // 這次取樣的延遲 (秒),取樣當下就決定好
}
[Header("參照")]
public BotSpawner spawner;
[Tooltip("Main Camera (外掛看到的畫面)")]
public Camera viewCamera;
[Tooltip("Player 根物件,判斷遮擋時略過自己")]
public Transform playerRoot;
[Header("視覺特性")]
[Tooltip("被擋住超過這個比例就偵測不到")]
[Range(0f, 1f)] public float maxOccludedRatio = 0.25f;
[Header("測試")]
[Tooltip("在畫面左上角顯示偵測狀態,並在偵測到的胸口位置畫一個框")]
public bool showDebug = true;
public Detection Truth { get; private set; } // 每一幀的真值 (完美感知器)
public Detection Output { get; private set; } // 經過取樣與延遲,輔助真正拿到的結果
public float DelayMs { get; private set; }
private float sampleInterval; // 0 = 每一幀
private float nextSampleTime;
private int baseDelayMs;
private int jitterMs;
private System.Random jitterRandom = new System.Random(); // 延遲抖動專用,跟機器人的亂數分開
private readonly Queue<Detection> pending = new Queue<Detection>();
// 各部位佔整個人的比例 (大約是人的外形面積),取樣點的權重照這個分配
// 不加權的話,腿有 4 個命中框、佔了大部分取樣點,地上一點小起伏就會讓整個人判定成被擋住
private const float HeadShare = 0.15f;
private const float BodyShare = 0.45f;
private const float LegShare = 0.40f;
private readonly List<Vector3> samplePoints = new List<Vector3>();
private readonly List<BodyPart> sampleParts = new List<BodyPart>();
private readonly List<float> sampleWeights = new List<float>();
private string lastBlocker = ""; // 除錯用 : 這一幀擋住最多取樣點的物件
private readonly RaycastHit[] hitBuffer = new RaycastHit[16];
void Start()
{
// 沒拖、或拖到 prefab 檔案本身 : 自動找場景裡的 BotSpawner (新地圖不用再手動接)
spawner = BotSpawner.FindInScene(spawner);
// 延遲與抖動由 Apply() 每回合套上,不在這裡讀
GameSettings settings = GameSettings.Load();
int refreshRate = settings.refreshRate > 0 ? settings.refreshRate : 60;
sampleInterval = SessionPlan.IsAuto(settings) ? 0f : 1f / refreshRate;
}
// 套用這一回合的延遲條件,並清掉上一回合的辨識結果 (BotSpawner 在通知記錄器之前呼叫)
public void Apply(SessionPlan.RoundCondition c)
{
baseDelayMs = c.assistDelayMs;
jitterMs = c.assistDelayJitterMs;
jitterRandom = new System.Random(c.roundSeed ^ 0x5bd1e995); // 跟後座力 (直接用 roundSeed) 錯開,不要變成同一串亂數
pending.Clear();
Output = default;
DelayMs = 0f;
nextSampleTime = 0f;
}
void LateUpdate()
{
// LateUpdate : 等視角和敵人都更新完,才是這一幀畫面上的樣子
Truth = Perceive();
// 暫停時 Time.time 不會前進,不取樣
if (!PauseMenu.IsPaused && Time.time >= nextSampleTime)
{
nextSampleTime = Time.time + sampleInterval;
// 抖動 : 每次取樣的延遲在 ±jitterMs 內隨機 (模擬視覺模型推論時間不穩) ; 不會小於 0
Detection sample = Truth;
sample.delay = Mathf.Max(0f, baseDelayMs + ((float)jitterRandom.NextDouble() * 2f - 1f) * jitterMs) / 1000f;
pending.Enqueue(sample);
}
// 延遲 : 擷取時間 + 延遲 到了才交出去
while (pending.Count > 0 && Time.time - pending.Peek().captureTime >= pending.Peek().delay)
{
Output = pending.Dequeue();
DelayMs = Output.delay * 1000f;
}
}
Detection Perceive()
{
Detection d = new Detection { captureTime = Time.time };
BotHealth bot = spawner != null ? spawner.CurrentBot : null;
if (bot == null || viewCamera == null) return d;
Hitbox chest = CollectSamplePoints(bot);
if (chest == null || samplePoints.Count == 0) return d;
// 遮擋比例 : 每個取樣點都從相機拉一條線,中間被別的東西擋住或在畫面外就算看不到 (依權重加總)
float visible = 0f, total = 0f;
blockerCounts.Clear();
for (int i = 0; i < samplePoints.Count; i++)
{
total += sampleWeights[i];
if (IsPointVisible(samplePoints[i], bot.transform)) visible += sampleWeights[i];
}
d.visibleRatio = total > 0f ? visible / total : 0f;
lastBlocker = MostCommonBlocker();
// 胸口的角度與螢幕座標
Vector3 chestPos = chest.GetComponent<Collider>().bounds.center;
Vector3 local = viewCamera.transform.InverseTransformPoint(chestPos);
d.angleError = new Vector2(
Mathf.Atan2(local.x, local.z) * Mathf.Rad2Deg,
Mathf.Atan2(local.y, new Vector2(local.x, local.z).magnitude) * Mathf.Rad2Deg);
Vector3 screen = viewCamera.WorldToScreenPoint(chestPos);
d.screenOffset = new Vector2(screen.x - Screen.width * 0.5f, screen.y - Screen.height * 0.5f);
d.detected = local.z > 0f && d.visibleRatio >= 1f - maxOccludedRatio;
return d;
}
// 取樣點 : 每個命中框的中心,身體和腿再加上下兩端 ; 回傳身體 (胸口) 的命中框
// 權重 : 每個部位的比例平均分給該部位的所有取樣點 (例如 4 個腿命中框共 12 點,平分 40%)
Hitbox CollectSamplePoints(BotHealth bot)
{
samplePoints.Clear();
sampleParts.Clear();
sampleWeights.Clear();
Hitbox chest = null;
int headPoints = 0, bodyPoints = 0, legPoints = 0;
foreach (Hitbox hitbox in bot.GetComponentsInChildren<Hitbox>())
{
if (!hitbox.TryGetComponent(out Collider col) || !col.enabled) continue;
Bounds b = col.bounds;
int added = 1;
samplePoints.Add(b.center);
if (hitbox.part != BodyPart.Head)
{
samplePoints.Add(b.center + Vector3.up * b.extents.y * 0.7f);
samplePoints.Add(b.center - Vector3.up * b.extents.y * 0.7f);
added = 3;
}
for (int i = 0; i < added; i++) sampleParts.Add(hitbox.part);
if (hitbox.part == BodyPart.Head) headPoints += added;
else if (hitbox.part == BodyPart.Body) bodyPoints += added;
else legPoints += added;
if (hitbox.part == BodyPart.Body) chest = hitbox;
}
foreach (BodyPart part in sampleParts)
{
if (part == BodyPart.Head) sampleWeights.Add(HeadShare / headPoints);
else if (part == BodyPart.Body) sampleWeights.Add(BodyShare / bodyPoints);
else sampleWeights.Add(LegShare / legPoints);
}
return chest;
}
private readonly Dictionary<string, int> blockerCounts = new Dictionary<string, int>();
string MostCommonBlocker()
{
string best = ""; int bestCount = 0;
foreach (KeyValuePair<string, int> kv in blockerCounts)
{
if (kv.Value > bestCount) { best = kv.Key; bestCount = kv.Value; }
}
return bestCount > 0 ? $"{best} ({bestCount} 點)" : "";
}
void OnGUI()
{
if (!showDebug) return;
GUI.Label(new Rect(10, 10, 600, 22),
$"真值 : {(Truth.detected ? "偵測到" : "沒偵測到")} 可見 {Truth.visibleRatio:P0} | 外掛拿到 : {(Output.detected ? "偵測到" : "沒偵測到")} 延遲 {DelayMs:F0}ms");
if (!string.IsNullOrEmpty(lastBlocker))
{
GUI.Label(new Rect(10, 30, 600, 22), $"擋住最多的物件 : {lastBlocker}");
}
// 外掛拿到的胸口位置 (GUI 的 y 軸往下,所以要翻過來)
if (Output.detected)
{
float x = Screen.width * 0.5f + Output.screenOffset.x;
float y = Screen.height * 0.5f - Output.screenOffset.y;
GUI.Box(new Rect(x - 10, y - 10, 20, 20), "");
}
}
bool IsPointVisible(Vector3 point, Transform bot)
{
Vector3 vp = viewCamera.WorldToViewportPoint(point);
if (vp.z <= 0f || vp.x < 0f || vp.x > 1f || vp.y < 0f || vp.y > 1f) return false;
Vector3 origin = viewCamera.transform.position;
Vector3 toPoint = point - origin;
int count = Physics.RaycastNonAlloc(origin, toPoint.normalized, hitBuffer, toPoint.magnitude, ~0, QueryTriggerInteraction.Ignore);
for (int i = 0; i < count; i++)
{
Transform t = hitBuffer[i].collider.transform;
if (t.IsChildOf(bot)) continue; // 機器人自己的移動膠囊
if (playerRoot != null && t.IsChildOf(playerRoot)) continue; // 玩家自己
// 被牆或障礙物擋住 ; 記下是誰擋的 (除錯用)
string name = hitBuffer[i].collider.name;
blockerCounts[name] = blockerCounts.TryGetValue(name, out int n) ? n + 1 : 1;
return false;
}
return true;
}
}