From e25e8aeec5f9d8e37f520ec2743924df0100a57c Mon Sep 17 00:00:00 2001 From: sthkm3 Date: Wed, 21 Oct 2026 13:46:03 +0800 Subject: [PATCH] add aim assist --- Assets/Scenes/StartUI.unity | 2 +- Assets/Scenes/Test.unity | 69 ++++++- Assets/Stript/InGame/Assist.meta | 8 + Assets/Stript/InGame/Assist/AimAssist.cs | 109 +++++++++++ Assets/Stript/InGame/Assist/AimAssist.cs.meta | 2 + Assets/Stript/InGame/Assist/EnemyPerceptor.cs | 173 ++++++++++++++++++ .../InGame/Assist/EnemyPerceptor.cs.meta | 2 + README.md | 10 +- 8 files changed, 368 insertions(+), 7 deletions(-) create mode 100644 Assets/Stript/InGame/Assist.meta create mode 100644 Assets/Stript/InGame/Assist/AimAssist.cs create mode 100644 Assets/Stript/InGame/Assist/AimAssist.cs.meta create mode 100644 Assets/Stript/InGame/Assist/EnemyPerceptor.cs create mode 100644 Assets/Stript/InGame/Assist/EnemyPerceptor.cs.meta diff --git a/Assets/Scenes/StartUI.unity b/Assets/Scenes/StartUI.unity index 141190d..5a901bb 100644 --- a/Assets/Scenes/StartUI.unity +++ b/Assets/Scenes/StartUI.unity @@ -17820,7 +17820,7 @@ MonoBehaviour: onValueChanged: m_PersistentCalls: m_Calls: [] - m_IsOn: 0 + m_IsOn: 1 --- !u!1 &1922218177 GameObject: m_ObjectHideFlags: 0 diff --git a/Assets/Scenes/Test.unity b/Assets/Scenes/Test.unity index 4abe2ff..29a1d49 100644 --- a/Assets/Scenes/Test.unity +++ b/Assets/Scenes/Test.unity @@ -1676,6 +1676,17 @@ MeshFilter: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 524565165} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!114 &547904313 stripped +MonoBehaviour: + m_CorrespondingSourceObject: {fileID: 879551139689297706, guid: f9ebddc774e381740b975be07f15dad6, type: 3} + m_PrefabInstance: {fileID: 3831511155047552199} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a0e8cd6eccf4349438a7eb38773f9923, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::PlayerLook --- !u!1 &573989629 GameObject: m_ObjectHideFlags: 0 @@ -2359,6 +2370,11 @@ MeshFilter: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 794873812} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!1 &799735551 stripped +GameObject: + m_CorrespondingSourceObject: {fileID: 140497572222575882, guid: f9ebddc774e381740b975be07f15dad6, type: 3} + m_PrefabInstance: {fileID: 3831511155047552199} + m_PrefabAsset: {fileID: 0} --- !u!1 &815983305 GameObject: m_ObjectHideFlags: 0 @@ -2902,6 +2918,11 @@ MeshFilter: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1402397389} m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0} +--- !u!20 &1486141219 stripped +Camera: + m_CorrespondingSourceObject: {fileID: 7876713027733882114, guid: f9ebddc774e381740b975be07f15dad6, type: 3} + m_PrefabInstance: {fileID: 3831511155047552199} + m_PrefabAsset: {fileID: 0} --- !u!1 &1553659633 GameObject: m_ObjectHideFlags: 0 @@ -3741,6 +3762,10 @@ PrefabInstance: propertyPath: spawner value: objectReference: {fileID: 727757762} + - target: {fileID: 7732910103433979680, guid: f9ebddc774e381740b975be07f15dad6, type: 3} + propertyPath: k__BackingField + value: 0 + objectReference: {fileID: 0} - target: {fileID: 8881686795909946582, guid: f9ebddc774e381740b975be07f15dad6, type: 3} propertyPath: m_LocalPosition.x value: 0 @@ -3784,13 +3809,55 @@ PrefabInstance: m_RemovedComponents: [] m_RemovedGameObjects: [] m_AddedGameObjects: [] - m_AddedComponents: [] + m_AddedComponents: + - targetCorrespondingSourceObject: {fileID: 140497572222575882, guid: f9ebddc774e381740b975be07f15dad6, type: 3} + insertIndex: -1 + addedObject: {fileID: 4147227459518174560} + - targetCorrespondingSourceObject: {fileID: 140497572222575882, guid: f9ebddc774e381740b975be07f15dad6, type: 3} + insertIndex: -1 + addedObject: {fileID: 4147227459518174559} m_SourcePrefab: {fileID: 100100000, guid: f9ebddc774e381740b975be07f15dad6, type: 3} --- !u!4 &4147227459518174557 stripped Transform: m_CorrespondingSourceObject: {fileID: 8881686795909946582, guid: f9ebddc774e381740b975be07f15dad6, type: 3} m_PrefabInstance: {fileID: 3831511155047552199} m_PrefabAsset: {fileID: 0} +--- !u!114 &4147227459518174559 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 799735551} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 933227a32aaccbb479622ad6814d2780, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::AimAssist + perceptor: {fileID: 4147227459518174560} + playerLook: {fileID: 547904313} + minFov: 3 + maxFov: 15 + trackSpeed: {x: 2, y: 30} + minSensitivityScale: 0.1 + innerAngle: 2 +--- !u!114 &4147227459518174560 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 799735551} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7ab130dbf846dca43aef48810a10ac26, type: 3} + m_Name: + m_EditorClassIdentifier: Assembly-CSharp::EnemyPerceptor + spawner: {fileID: 727757762} + viewCamera: {fileID: 1486141219} + playerRoot: {fileID: 4147227459518174557} + maxOccludedRatio: 0.25 + showDebug: 1 --- !u!1001 &4458914454911198105 PrefabInstance: m_ObjectHideFlags: 0 diff --git a/Assets/Stript/InGame/Assist.meta b/Assets/Stript/InGame/Assist.meta new file mode 100644 index 0000000..3b926b2 --- /dev/null +++ b/Assets/Stript/InGame/Assist.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 67f95fe0f6e85194c9594737ac7086a8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Stript/InGame/Assist/AimAssist.cs b/Assets/Stript/InGame/Assist/AimAssist.cs new file mode 100644 index 0000000..bb6ea3a --- /dev/null +++ b/Assets/Stript/InGame/Assist/AimAssist.cs @@ -0,0 +1,109 @@ +using UnityEngine; + +// 模擬 AI 視覺外掛的輔助瞄準 : 只用 EnemyPerceptor.Output (外掛真正拿到的結果) +// 模式依 StartUI 設定 : 0 = 無輔助,1 = 平滑跟槍,2 = 動態靈敏度 +public class AimAssist : MonoBehaviour +{ + [Header("參照")] + public EnemyPerceptor perceptor; + + [Tooltip("CameraRoot 上的 PlayerLook")] + public PlayerLook playerLook; + + [Header("輔助範圍 (準心周圍一圈,半徑隨強度變大)")] + [Tooltip("強度 1% 時的半徑 (度)")] + public float minFov = 3f; + + [Tooltip("強度 100% 時的半徑 (度)")] + public float maxFov = 15f; + + [Header("平滑跟槍")] + [Tooltip("強度 1% / 100% 時的修正速度 (每秒修正剩餘誤差的比例係數,越大越快)")] + public Vector2 trackSpeed = new Vector2(2f, 30f); + + [Header("動態靈敏度 (沒有範圍限制,偵測到就生效)")] + [Tooltip("強度 100% 時,準心貼在敵人身上的靈敏度倍率")] + [Range(0f, 1f)] public float minSensitivityScale = 0.1f; + + [Tooltip("離胸口這個角度以內都維持最低靈敏度 (度),大約是身體的寬度")] + public float innerAngle = 2f; + + // 給記錄器用 : 這一幀輔助做了什麼 + public float FovRadius { get; private set; } + public bool Engaged { get; private set; } + + private int mode; + private float strength; // 0~1 + private bool noHorizontal; + private bool noVertical; + private float degreesPerCount; + private float lastSampleTime = -1f; + private Vector2 remainingError; // 平滑跟槍 : 這次取樣還沒修正完的誤差 (度) + + void Start() + { + GameSettings s = GameSettings.Load(); + mode = s.assistMode; + strength = s.assistStrength / 100f; + noHorizontal = s.disableHorizontalAssist; + noVertical = s.disableVerticalAssist; + degreesPerCount = 0.022f * Mathf.Max(0.01f, s.sensitivity); // 跟 PlayerLook 相同的換算 + + FovRadius = Mathf.Lerp(minFov, maxFov, strength); + } + + void Update() + { + Engaged = false; + if (mode == 0 || perceptor == null || playerLook == null) return; + + EnemyPerceptor.Detection d = perceptor.Output; + Vector2 error = d.angleError; + if (noHorizontal) error.x = 0f; + if (noVertical) error.y = 0f; + + bool inRange = d.detected && d.angleError.magnitude <= FovRadius; + + if (mode == 1) SmoothTrack(d, error, inRange); + else if (mode == 2) DynamicSensitivity(d); + } + + // 平滑跟槍 : 每次拿到新的辨識結果,就把那時候的誤差一點一點補到滑鼠上 + // 外掛只知道擷取當下的誤差,所以兩次辨識之間不會更新 (延遲越大越容易過頭) + void SmoothTrack(EnemyPerceptor.Detection d, Vector2 error, bool inRange) + { + if (!Mathf.Approximately(d.captureTime, lastSampleTime)) + { + lastSampleTime = d.captureTime; + remainingError = inRange ? error : Vector2.zero; + } + + if (remainingError == Vector2.zero) return; + + float speed = Mathf.Lerp(trackSpeed.x, trackSpeed.y, strength); + Vector2 step = remainingError * (1f - Mathf.Exp(-speed * Time.deltaTime)); + remainingError -= step; + + playerLook.AddAssistDelta(step / degreesPerCount); // 度 → 滑鼠單位 + Engaged = true; + } + + // 動態靈敏度 : 準心越靠近敵人,靈敏度越低 (像手把輔瞄的阻尼感) + // 胸口附近 innerAngle 內維持最低,往畫面邊緣慢慢恢復,到畫面邊緣 = 正常靈敏度 ; 沒偵測到 = 正常 + void DynamicSensitivity(EnemyPerceptor.Detection d) + { + float scale = 1f; + if (d.detected && perceptor.viewCamera != null) + { + Camera cam = perceptor.viewCamera; + float halfScreen = Camera.VerticalToHorizontalFieldOfView(cam.fieldOfView, cam.aspect) * 0.5f; + float t = Mathf.Clamp01((d.angleError.magnitude - innerAngle) / Mathf.Max(1f, halfScreen - innerAngle)); + + float lowest = Mathf.Lerp(1f, minSensitivityScale, strength); + scale = Mathf.Lerp(lowest, 1f, t); + Engaged = true; + } + + playerLook.sensitivityScale = scale; + } +} diff --git a/Assets/Stript/InGame/Assist/AimAssist.cs.meta b/Assets/Stript/InGame/Assist/AimAssist.cs.meta new file mode 100644 index 0000000..a6314d1 --- /dev/null +++ b/Assets/Stript/InGame/Assist/AimAssist.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 933227a32aaccbb479622ad6814d2780 \ No newline at end of file diff --git a/Assets/Stript/InGame/Assist/EnemyPerceptor.cs b/Assets/Stript/InGame/Assist/EnemyPerceptor.cs new file mode 100644 index 0000000..1a0789a --- /dev/null +++ b/Assets/Stript/InGame/Assist/EnemyPerceptor.cs @@ -0,0 +1,173 @@ +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; + } +} diff --git a/Assets/Stript/InGame/Assist/EnemyPerceptor.cs.meta b/Assets/Stript/InGame/Assist/EnemyPerceptor.cs.meta new file mode 100644 index 0000000..ba59e3d --- /dev/null +++ b/Assets/Stript/InGame/Assist/EnemyPerceptor.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7ab130dbf846dca43aef48810a10ac26 \ No newline at end of file diff --git a/README.md b/README.md index 376562e..a9ec933 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ![StartUI 畫面](png/001.png) -> ⚠️ 專案仍在開發中,尚未發布可遊玩的版本。 +> 專案仍在開發中,尚未發布可遊玩的版本。 --- @@ -23,9 +23,9 @@ | 第一人稱視角(Apex 靈敏度與 FOV 換算) | 完成 | | 武器與射擊 | 完成 | | 敵人 / 移動靶 | 完成 | -| 模擬視覺模型與輔助瞄準 | 目前 | +| 模擬視覺模型與輔助瞄準 | 開發中 | | 軌跡記錄器與資料匯出 | 未開始 | -| 正式地圖(森林、地下室、沙漠) | 未開始 | +| 正式地圖(森林、地下室、沙漠) | 開發中 | --- @@ -35,10 +35,10 @@ | 按鍵 | 動作 | |---|---| -| WASD | 移動(按 W 時自動衝刺) | +| WASD | 移動(前進時自動奔跑) | | 滑鼠 | 瞄準 | | Space | 跳躍 | -| Left Shift | 蹲下 / 滑鏟(衝刺中按下) | +| Left Shift | 蹲下 / 滑鏟(奔跑中按下) | | R | 換彈 | | Esc | 退出 |