Unity中NavMeshAgent敌人碰撞玩家时X轴旋转异常求助
我在Unity项目中遇到一个问题:带有NavMeshAgent组件的敌人与玩家发生碰撞时,其旋转的X值会变为-180,但我需要该值固定保持在-90。尝试了多种方法都没能解决,以下是对应的代码及问题截图,求帮忙解决:
using UnityEngine; using UnityEngine.AI; public class Enemy : MonoBehaviour { public NavMeshAgent agent; public Transform player; public float chaseCooldownTime = 3f; // Adjust this as needed private bool canChase = true; private Quaternion targetRotation; void Update() { if (player && canChase) { // Set destination for NavMeshAgent agent.SetDestination(player.position); // Rotate towards player RotateTowardsPlayer(); } } void LateUpdate() { if (player != null && canChase) { // Apply rotation to the enemy without changing the pitch or roll transform.rotation = Quaternion.Euler(targetRotation.eulerAngles.x -90, targetRotation.eulerAngles.y + 90, 0); } } void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Player")) { canChase = false; Invoke("ResetChase", chaseCooldownTime); } } void ResetChase() { canChase = true; } void RotateTowardsPlayer() { // Calculate direction from enemy to player Vector3 directionToPlayer = player.position - transform.position; directionToPlayer.y = 0; // Ignore vertical component // Calculate rotation to face player targetRotation = Quaternion.LookRotation(directionToPlayer); } }

问题原因及解决方法
问题根源是碰撞后canChase变为false,LateUpdate中的旋转控制代码停止执行,同时NavMeshAgent默认会自动调整物体旋转朝向移动方向,导致X轴角度偏离预期的-90。
具体解决方案:
- 禁用NavMeshAgent自动旋转:阻止组件自动修改物体旋转,完全由代码控制角度。
- 强制锁定X轴旋转:无论是否处于追逐状态,都固定X轴为-90,避免碰撞或其他行为干扰。
修改后的完整代码:
using UnityEngine; using UnityEngine.AI; public class Enemy : MonoBehaviour { public NavMeshAgent agent; public Transform player; public float chaseCooldownTime = 3f; private bool canChase = true; private Quaternion targetRotation; void Start() { // 关闭NavMeshAgent的自动旋转功能 agent.updateRotation = false; } void Update() { if (player && canChase) { agent.SetDestination(player.position); RotateTowardsPlayer(); } } void LateUpdate() { Quaternion finalRotation = transform.rotation; if (player != null && canChase) { // 追逐状态下,保持X轴-90,根据目标更新Y轴旋转 finalRotation = Quaternion.Euler(-90f, targetRotation.eulerAngles.y + 90f, 0f); } else { // 非追逐状态下,仅固定X轴为-90,保留当前Y、Z轴旋转 finalRotation = Quaternion.Euler(-90f, finalRotation.eulerAngles.y, finalRotation.eulerAngles.z); } transform.rotation = finalRotation; } void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Player")) { canChase = false; Invoke("ResetChase", chaseCooldownTime); } } void ResetChase() { canChase = true; } void RotateTowardsPlayer() { Vector3 directionToPlayer = player.position - transform.position; directionToPlayer.y = 0; targetRotation = Quaternion.LookRotation(directionToPlayer); } }
关键修改说明:
agent.updateRotation = false:彻底禁用NavMeshAgent的自动旋转,避免组件擅自修改物体角度。- 固定X轴旋转:在
LateUpdate中始终将X轴设置为-90,无论是否在追逐状态,确保角度不会被其他因素改变。 - 移除可变X轴计算:原代码中依赖
targetRotation.x的计算被替换为固定值,消除了角度波动的可能。
这样修改后,敌人的X轴旋转会始终保持在-90,碰撞玩家后也不会出现异常偏移。
内容的提问来源于stack exchange,提问作者Kush N
相关产品推荐
相关产品推荐

