From 3ca78168748731fff88097cba0e27058526bcde5 Mon Sep 17 00:00:00 2001 From: ngtuanz1 Date: Fri, 5 Jun 2026 23:25:56 +0700 Subject: [PATCH] update --- .idea/.idea.HALLUCINATE/.idea/workspace.xml | 36 +-- Assets/Scripts/AI NPC/AnimatorAI.cs | 341 +++++++------------- Assets/Scripts/AI NPC/EnemyAI.cs | 3 + 3 files changed, 125 insertions(+), 255 deletions(-) diff --git a/.idea/.idea.HALLUCINATE/.idea/workspace.xml b/.idea/.idea.HALLUCINATE/.idea/workspace.xml index 5a086632..11f41985 100644 --- a/.idea/.idea.HALLUCINATE/.idea/workspace.xml +++ b/.idea/.idea.HALLUCINATE/.idea/workspace.xml @@ -6,34 +6,8 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + @@ -204,6 +179,7 @@ + diff --git a/Assets/Scripts/AI NPC/AnimatorAI.cs b/Assets/Scripts/AI NPC/AnimatorAI.cs index 12657a1c..c7dc4663 100644 --- a/Assets/Scripts/AI NPC/AnimatorAI.cs +++ b/Assets/Scripts/AI NPC/AnimatorAI.cs @@ -1,307 +1,199 @@ using UnityEngine; using UnityEngine.AI; using Invector; +using Invector.vEventSystems; using System.Collections; /// -/// AnimatorAI: Đồng bộ hóa trạng thái của EnemyAI với Animator. -/// Tích hợp Simulation Mode để giả lập animation khi chưa có logic di chuyển hoàn chỉnh. +/// AnimatorAI: Advanced Invector-style Animator synchronization for EnemyAI. +/// Resolves T-pose by ensuring all core Invector parameters are correctly synced. /// -public class AnimatorAI : MonoBehaviour +public class AnimatorAI : MonoBehaviour, vIAnimatorStateInfoController { protected Animator animator; protected EnemyAI enemyAI; protected NavMeshAgent agent; protected Rigidbody rb; - - [Header("Debug Settings")] - public bool debugMode = true; - public Color debugColor = Color.cyan; - - [Header("Simulation Mode (Giả lập)")] - public bool useSimulation = false; // Tích chọn để dùng thông số giả lập bên dưới - public bool autoCycleSpeed = false; // Tự động chạy/đi bộ/đứng im theo vòng lặp - [Range(0, 1)] public float simVerticalVelocity = 0f; - public bool simIsSprinting = false; - public bool simIsAiming = false; - public int simMoveSetID = 0; + protected vHealthController healthController; [Header("Movement Settings")] public float sprintThreshold = 0.8f; public float dampTime = 0.1f; + public float groundDistanceValue = 0.05f; + + public vAnimatorStateInfos animatorStateInfos { get; protected set; } #region Animator Parameters (Invector Style) protected vAnimatorParameter isDead; protected vAnimatorParameter isGrounded; - protected vAnimatorParameter isCrouching; protected vAnimatorParameter isStrafing; - protected vAnimatorParameter isSliding; protected vAnimatorParameter isSprinting; protected vAnimatorParameter isAiming; - protected vAnimatorParameter canAim; - protected vAnimatorParameter flipAnimation; - protected vAnimatorParameter flipEquip; - protected vAnimatorParameter groundDistance; - protected vAnimatorParameter groundAngle; protected vAnimatorParameter verticalVelocity; + protected vAnimatorParameter horizontalVelocity; + protected vAnimatorParameter groundDistance; protected vAnimatorParameter moveSet_ID; - protected vAnimatorParameter upperBody_ID; - protected vAnimatorParameter idleRandom; - protected vAnimatorParameter idleRandomTrigger; - protected vAnimatorParameter randomAttack; - protected vAnimatorParameter weakAttack; - protected vAnimatorParameter strongAttack; - protected vAnimatorParameter isBlocking; protected vAnimatorParameter attackID; - protected vAnimatorParameter defenseID; - protected vAnimatorParameter recoilID; - protected vAnimatorParameter reactionID; - protected vAnimatorParameter triggerRecoil; - protected vAnimatorParameter triggerReaction; protected vAnimatorParameter hitDirection; + protected vAnimatorParameter reactionID; + protected vAnimatorParameter triggerReaction; protected vAnimatorParameter resetState; - protected vAnimatorParameter reload; - protected vAnimatorParameter cancelReload; - protected vAnimatorParameter reloadID; - protected vAnimatorParameter shoot; - protected vAnimatorParameter shot_ID; - protected vAnimatorParameter powerCharger; #endregion - [Header("Nuclear Diagnostic (Siêu chẩn đoán)")] - public string forcePlayState = ""; // Gõ tên State vào đây để ép nó chạy (vd: Idle) - public bool showLayerWeights = false; + protected Vector3 lastPosition; + protected float currentV; + protected float currentH; - protected virtual void Start() + protected virtual void Awake() { animator = GetComponentInChildren(); enemyAI = GetComponent(); agent = GetComponent(); rb = GetComponent(); + healthController = GetComponent(); - if (animator == null) + if (animator) { - Debug.LogError($"[AnimatorAI] KHÔNG tìm thấy Animator trên {gameObject.name} hoặc các con của nó!"); - return; + animatorStateInfos = new vAnimatorStateInfos(animator); + InitializeParameters(); } - // Chạy chẩn đoán hạt nhân - StartCoroutine(NuclearDiagnosticRoutine()); - - InitializeParameters(); + lastPosition = transform.position; } - private IEnumerator NuclearDiagnosticRoutine() + protected virtual void OnEnable() { - while (true) - { - yield return new WaitForSeconds(1f); + this.Register(); + if (healthController) healthController.onReceiveDamage.AddListener(OnReceiveDamage); + } - if (animator == null) yield break; - - // 1. Kiểm tra Enabled - if (!animator.enabled) - Debug.LogError($"[NUCLEAR ALERT] Component Animator đang bị TẮT (enabled = false)!"); - - // 2. Kiểm tra Rig Type - if (animator.isHuman) - Debug.Log($"[Rig Info] Rig là Humanoid. Hãy chắc chắn các Animation cũng là Humanoid."); - else - Debug.LogWarning($"[Rig Info] Rig là Generic/Legacy. Nếu bạn dùng Animation Humanoid nó sẽ không chạy."); - - // 3. Kiểm tra Layer Weight - if (showLayerWeights) - { - for (int i = 0; i < animator.layerCount; i++) - { - Debug.Log($"Layer {i} ({animator.GetLayerName(i)}): Weight = {animator.GetLayerWeight(i)}"); - } - } - - // 4. Ép chạy State nếu có yêu cầu - if (!string.IsNullOrEmpty(forcePlayState)) - { - Debug.Log($"[Nuclear Force] ÉP CHẠY STATE: {forcePlayState}"); - animator.Play(forcePlayState); - forcePlayState = ""; // Reset sau khi chạy - } - - // 5. Kiểm tra vị trí xương (Nếu T-pose thì thường xương không đổi vị trí) - Vector3 handPos = animator.GetBoneTransform(HumanBodyBones.RightHand) ? animator.GetBoneTransform(HumanBodyBones.RightHand).position : Vector3.zero; - yield return new WaitForSeconds(0.1f); - if (handPos != Vector3.zero && Vector3.Distance(handPos, animator.GetBoneTransform(HumanBodyBones.RightHand).position) < 0.001f && animator.speed > 0) - { - // Nếu xương không nhúc nhích dù tốc độ > 0 - Debug.LogWarning($"[NUCLEAR ALERT] CẢNH BÁO: Xương nhân vật không nhúc nhích! Có thể do Rig lỗi hoặc bị script khác khóa xương."); - } - - if (!useSimulation) yield break; - } + protected virtual void OnDisable() + { + this.UnRegister(); + if (healthController) healthController.onReceiveDamage.RemoveListener(OnReceiveDamage); } protected virtual void InitializeParameters() { - if (animator == null) return; - - // Khởi tạo và kiểm tra từng tham số quan trọng - isDead = ValidateAndInit("isDead"); - isGrounded = ValidateAndInit("IsGrounded"); - isCrouching = ValidateAndInit("IsCrouching"); - isStrafing = ValidateAndInit("IsStrafing"); - isSliding = ValidateAndInit("IsSliding"); - isSprinting = ValidateAndInit("IsSprinting"); - isAiming = ValidateAndInit("IsAiming"); - canAim = ValidateAndInit("CanAim"); - flipAnimation = ValidateAndInit("FlipAnimation"); - flipEquip = ValidateAndInit("FlipEquip"); - groundDistance = ValidateAndInit("GroundDistance"); - groundAngle = ValidateAndInit("GroundAngle"); - verticalVelocity = ValidateAndInit("VerticalVelocity"); - moveSet_ID = ValidateAndInit("MoveSet_ID"); - upperBody_ID = ValidateAndInit("UpperBody_ID"); - idleRandom = ValidateAndInit("IdleRandom"); - idleRandomTrigger = ValidateAndInit("IdleRandomTrigger"); - randomAttack = ValidateAndInit("RandomAttack"); - weakAttack = ValidateAndInit("WeakAttack"); - strongAttack = ValidateAndInit("StrongAttack"); - isBlocking = ValidateAndInit("IsBlocking"); - attackID = ValidateAndInit("AttackID"); - defenseID = ValidateAndInit("DefenseID"); - recoilID = ValidateAndInit("RecoilID"); - reactionID = ValidateAndInit("ReactionID"); - triggerRecoil = ValidateAndInit("TriggerRecoil"); - triggerReaction = ValidateAndInit("TriggerReaction"); - hitDirection = ValidateAndInit("HitDirection"); - resetState = ValidateAndInit("ResetState"); - reload = ValidateAndInit("Reload"); - cancelReload = ValidateAndInit("CancelReload"); - reloadID = ValidateAndInit("ReloadID"); - shoot = ValidateAndInit("Shoot"); - shot_ID = ValidateAndInit("Shot_ID"); - powerCharger = ValidateAndInit("PowerCharger"); - } - - private vAnimatorParameter ValidateAndInit(string paramName) - { - vAnimatorParameter p = new vAnimatorParameter(animator, paramName); - if (!p.isValid && debugMode) - { - // Chỉ cảnh báo những biến cốt lõi nếu thiếu - if (paramName == "VerticalVelocity" || paramName == "IsGrounded" || paramName == "IsAiming") - Debug.LogWarning($"[AnimatorAI] Cảnh báo: Controller thiếu biến quan trọng: {paramName}"); - } - return p; + isDead = new vAnimatorParameter(animator, "isDead"); + isGrounded = new vAnimatorParameter(animator, "IsGrounded"); + isStrafing = new vAnimatorParameter(animator, "IsStrafing"); + isSprinting = new vAnimatorParameter(animator, "IsSprinting"); + isAiming = new vAnimatorParameter(animator, "IsAiming"); + verticalVelocity = new vAnimatorParameter(animator, "VerticalVelocity"); + horizontalVelocity = new vAnimatorParameter(animator, "HorizontalVelocity"); + groundDistance = new vAnimatorParameter(animator, "GroundDistance"); + moveSet_ID = new vAnimatorParameter(animator, "MoveSet_ID"); + attackID = new vAnimatorParameter(animator, "AttackID"); + hitDirection = new vAnimatorParameter(animator, "HitDirection"); + reactionID = new vAnimatorParameter(animator, "ReactionID"); + triggerReaction = new vAnimatorParameter(animator, "TriggerReaction"); + resetState = new vAnimatorParameter(animator, "ResetState"); } protected virtual void Update() { - if (animator == null) return; + if (animator == null || enemyAI == null || agent == null) return; - if (useSimulation) - { - RunSimulation(); - } - else - { - if (enemyAI == null || agent == null) return; - UpdateMovementParameters(); - UpdateCombatParameters(); - } - } - - protected virtual void RunSimulation() - { - // 1. Giả lập tốc độ di chuyển - if (autoCycleSpeed) - { - // Tạo vòng lặp tốc độ từ 0 đến 1 dùng hàm Sin - simVerticalVelocity = Mathf.Abs(Mathf.Sin(Time.time * 0.5f)); - simIsSprinting = simVerticalVelocity > sprintThreshold; - } - - SetFloat(verticalVelocity, simVerticalVelocity, "SIM: VerticalVelocity"); - SetBool(isSprinting, simIsSprinting, "SIM: IsSprinting"); - SetBool(isGrounded, true, "SIM: IsGrounded"); // Luôn giả lập trên mặt đất - - // 2. Giả lập chiến đấu - SetBool(isAiming, simIsAiming, "SIM: IsAiming"); - SetInt(moveSet_ID, simMoveSetID, "SIM: MoveSet_ID"); - SetBool(canAim, simIsAiming, "SIM: CanAim"); + UpdateMovementParameters(); + UpdateCombatParameters(); } protected virtual void UpdateMovementParameters() { + // 1. Grounded & GroundDistance (Critical for T-pose prevention) bool grounded = agent.isOnNavMesh || agent.enabled; - SetBool(isGrounded, grounded, "IsGrounded"); + SetBool(isGrounded, grounded); + SetFloat(groundDistance, grounded ? 0f : groundDistanceValue); - float speed = agent.velocity.magnitude / enemyAI.moveSpeed; - SetFloat(verticalVelocity, speed, "VerticalVelocity"); + // 2. Responsive Velocity Calculation + // Use a mix of agent velocity and position delta for better responsiveness + Vector3 worldVelocity = (transform.position - lastPosition) / Time.deltaTime; + lastPosition = transform.position; - bool sprinting = agent.velocity.magnitude > (enemyAI.moveSpeed * sprintThreshold); - SetBool(isSprinting, sprinting, "IsSprinting"); + if (worldVelocity.magnitude < 0.01f) worldVelocity = Vector3.zero; - bool isDodging = !agent.enabled && !rb.isKinematic; - SetBool(flipAnimation, isDodging, "FlipAnimation (Dodge)"); + Vector3 localVelocity = transform.InverseTransformDirection(worldVelocity); + + float targetV = localVelocity.z / enemyAI.moveSpeed; + float targetH = localVelocity.x / enemyAI.moveSpeed; + + // Smooth velocity values + currentV = Mathf.Lerp(currentV, targetV, 10f * Time.deltaTime); + currentH = Mathf.Lerp(currentH, targetH, 10f * Time.deltaTime); + + SetFloat(verticalVelocity, currentV); + SetFloat(horizontalVelocity, currentH); + + // 3. Sprinting + bool sprinting = worldVelocity.magnitude > (enemyAI.moveSpeed * sprintThreshold); + SetBool(isSprinting, sprinting); + + // 4. Strafing + SetBool(isStrafing, enemyAI.playerHasArtifact); } protected virtual void UpdateCombatParameters() { - bool aiming = enemyAI.playerHasArtifact && agent.isStopped; - SetBool(isAiming, aiming, "IsAiming"); + SetBool(isAiming, enemyAI.playerHasArtifact); + SetInt(moveSet_ID, enemyAI.playerHasArtifact ? 1 : 0); - int moveID = enemyAI.playerHasArtifact ? 1 : 0; - SetInt(moveSet_ID, moveID, "MoveSet_ID"); + // Shooting burst + if (enemyAI.IsShootingBurst) + SetInt(attackID, 1); + else + SetInt(attackID, 0); - SetBool(canAim, enemyAI.playerHasArtifact, "CanAim"); - } - - #region Optimized Setters with Debug - - protected void SetBool(vAnimatorParameter param, bool value, string name) - { - if (param.isValid) + // Dodge logic + if (enemyAI.IsDodging) { - bool current = animator.GetBool(param); - if (current != value) - { - animator.SetBool(param, value); - if (debugMode) Debug.Log($"[AnimDebug] {gameObject.name}: {name} -> {value}"); - } + // In Invector, dodges are often handled via triggers or specific IDs + SetAnimatorTrigger(triggerReaction); } + + // Death state + if (healthController) SetBool(isDead, healthController.isDead); } - protected void SetFloat(vAnimatorParameter param, float value, string name) + protected virtual void OnReceiveDamage(vDamage damage) + { + if (animator == null || !animator.enabled) return; + + // Sync damage parameters for hit reactions + if (hitDirection.isValid && damage.sender) + { + float angle = transform.HitAngle(damage.sender.position); + animator.SetInteger(hitDirection, (int)angle); + } + + if (reactionID.isValid) animator.SetInteger(reactionID, damage.reaction_id); + + SetAnimatorTrigger(triggerReaction); + SetAnimatorTrigger(resetState); + } + + #region Helpers + protected void SetBool(vAnimatorParameter param, bool value) + { + if (param.isValid && animator.GetBool(param) != value) + animator.SetBool(param, value); + } + + protected void SetFloat(vAnimatorParameter param, float value) { if (param.isValid) - { animator.SetFloat(param, value, dampTime, Time.deltaTime); - } } - protected void SetInt(vAnimatorParameter param, int value, string name) + protected void SetInt(vAnimatorParameter param, int value) { - if (param.isValid) - { - int current = animator.GetInteger(param); - if (current != value) - { - animator.SetInteger(param, value); - if (debugMode) Debug.Log($"[AnimDebug] {gameObject.name}: {name} -> {value}"); - } - } + if (param.isValid && animator.GetInteger(param) != value) + animator.SetInteger(param, value); } - #endregion - - #region Helper Methods (Triggers) - - public virtual void SetAnimatorTrigger(vAnimatorParameter trigger, string name = "Trigger") + public void SetAnimatorTrigger(vAnimatorParameter trigger) { - if (trigger.isValid) - { - if (debugMode) Debug.Log($"[AnimDebug] {gameObject.name}: Kích hoạt {name}"); - StartCoroutine(SetTriggerRoutine(trigger)); - } + if (trigger.isValid) StartCoroutine(SetTriggerRoutine(trigger)); } private IEnumerator SetTriggerRoutine(int targetHash) @@ -310,6 +202,5 @@ public class AnimatorAI : MonoBehaviour yield return new WaitForSeconds(0.1f); animator.ResetTrigger(targetHash); } - #endregion } diff --git a/Assets/Scripts/AI NPC/EnemyAI.cs b/Assets/Scripts/AI NPC/EnemyAI.cs index 8906a533..cd70cc88 100644 --- a/Assets/Scripts/AI NPC/EnemyAI.cs +++ b/Assets/Scripts/AI NPC/EnemyAI.cs @@ -63,6 +63,9 @@ public class EnemyAI : MonoBehaviour private int strafeDirectionSign = 1; // -1: Trái, 1: Phải, 0: Đứng im bắn private bool isShootingBurst = false; // Khóa chống trùng lặp loạt bắn + public bool IsDodging => isDodging; + public bool IsShootingBurst => isShootingBurst; + [Header("Conversation Settings")] public string npcName = "Guard"; [TextArea] public string persona = "You are a bored security guard. You love coffee and hate night shifts.";