大厂JAVA面试实录:Spring Boot、Redis缓存、Kafka异步与JVM调优(电商大促场景下的谢飞机)
2026/8/9 16:09:43
在游戏开发中,让角色智能地在场景中移动是提升沉浸感的关键。Unity的AI Navigation包通过导航网格(NavMesh)和寻路系统,让开发者轻松实现角色的自主导航。本文将基于官方文档,带你全面了解AI导航的核心概念、新功能、实践步骤,以及如何与动画系统耦合,打造更真实的角色行为。
AI导航系统主要解决两个问题:全局导航(如何推理目的地)和局部导航(如何移动到目的地)。
简单来说,NavMesh是“地图”,A*是“导航算法”,RVO是“避障机制”,三者协同让角色像真人一样在场景中移动。
2022年推出的1.1.1版本带来了多项实用更新,提升开发效率:
这些更新让导航系统的配置更智能,尤其适合复杂场景(如多层建筑、动态地形)。
导航网格是角色的“可行走地图”,需通过烘焙生成:
NavMesh Surface组件(Component > Navigation > NavMesh Surface)。Bake。烘焙后,场景中会显示蓝色叠加层(NavMesh),表示可行走区域。
代理是能自主移动的角色(如NPC、玩家):
NavMesh Agent组件(Component > Navigation > NavMesh Agent)。using UnityEngine; using UnityEngine.AI; public class MoveToClick : MonoBehaviour { NavMeshAgent agent; void Start() { agent = GetComponent<NavMeshAgent>(); } void Update() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out RaycastHit hit)) { agent.destination = hit.point; // 设置目的地 } } } }导航系统与动画结合,能避免“脚滑”等不自然现象。核心思路是用导航速度控制动画,或用动画位置更新导航。
创建包含“idle”(待机)和“move”(移动)状态的Animator Controller,通过velx(水平速度)、vely(垂直速度)参数控制动画过渡。
通过NavMeshAgent.velocity获取代理速度,传递给动画控制器;用OnAnimatorMove回调更新角色位置,确保动画与导航同步:
using UnityEngine; using UnityEngine.AI; public class LocomotionSimpleAgent : MonoBehaviour { NavMeshAgent agent; Animator anim; void Start() { agent = GetComponent<NavMeshAgent>(); anim = GetComponent<Animator>(); agent.updatePosition = false; // 关闭自动更新位置 } void Update() { // 计算代理速度 Vector3 worldDeltaPosition = agent.nextPosition - transform.position; float dx = Vector3.Dot(transform.right, worldDeltaPosition); float dy = Vector3.Dot(transform.forward, worldDeltaPosition); Vector2 deltaPosition = new Vector2(dx, dy); float smooth = Mathf.Min(1.0f, Time.deltaTime / 0.15f); smoothDeltaPosition = Vector2.Lerp(smoothDeltaPosition, deltaPosition, smooth); // 更新动画参数 anim.SetFloat("velx", smoothDeltaPosition.x); anim.SetFloat("vely", smoothDeltaPosition.y); } void OnAnimatorMove() { // 用动画位置更新角色位置 transform.position = agent.nextPosition; } }