using System.Collections.Generic; using UnityEngine; // 模擬 AI 視覺外掛的「眼睛」 // 1. 只在螢幕刷新時取樣 (外掛是擷取畫面,畫面一秒只更新刷新率那麼多次) // 2. 敵人被擋住 25% 以上就偵測不到 (視覺辨識的特性) // 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; private float nextSampleTime; private int baseDelayMs; private bool delayJitter; private readonly Queue pending = new Queue(); private readonly List samplePoints = new List(); private readonly RaycastHit[] hitBuffer = new RaycastHit[16]; void Start() { GameSettings settings = GameSettings.Load(); baseDelayMs = settings.assistDelayMs; delayJitter = settings.assistDelayJitter; int refreshRate = settings.refreshRate > 0 ? settings.refreshRate : 60; sampleInterval = 1f / refreshRate; } void LateUpdate() { // LateUpdate : 等視角和敵人都更新完,才是這一幀畫面上的樣子 Truth = Perceive(); if (Time.time >= nextSampleTime) { nextSampleTime = Time.time + sampleInterval; // 抖動 : 每次取樣 ±5ms Detection sample = Truth; sample.delay = Mathf.Max(0f, baseDelayMs + (delayJitter ? Random.Range(-5f, 5f) : 0f)) / 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; // 遮擋比例 : 每個取樣點都從相機拉一條線,中間被別的東西擋住或在畫面外就算看不到 int visible = 0; foreach (Vector3 p in samplePoints) { if (IsPointVisible(p, bot.transform)) visible++; } d.visibleRatio = (float)visible / samplePoints.Count; // 胸口的角度與螢幕座標 Vector3 chestPos = chest.GetComponent().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; } // 取樣點 : 每個命中框的中心,身體和腿再加上下兩端 ; 回傳身體 (胸口) 的命中框 Hitbox CollectSamplePoints(BotHealth bot) { samplePoints.Clear(); Hitbox chest = null; foreach (Hitbox hitbox in bot.GetComponentsInChildren()) { if (!hitbox.TryGetComponent(out Collider col) || !col.enabled) continue; Bounds b = col.bounds; 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); } if (hitbox.part == BodyPart.Body) chest = hitbox; } return chest; } void OnGUI() { if (!showDebug) return; GUI.Label(new Rect(10, 10, 600, 22), $"真值 : {(Truth.detected ? "偵測到" : "沒偵測到")} 可見 {Truth.visibleRatio:P0} | 外掛拿到 : {(Output.detected ? "偵測到" : "沒偵測到")} 延遲 {DelayMs:F0}ms 刷新 {1f / sampleInterval:F0}Hz"); // 外掛拿到的胸口位置 (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; // 玩家自己 return false; // 被牆或障礙物擋住 } return true; } }