Unity智能体运动AI脚本开发实战,从基础移动到智能导航
xwhb
2026-12-04
在游戏开发领域,智能体(Agent)的运动控制是AI系统的核心组成部分,无论是敌人的巡逻追击、NPC的自然行走,还是群体生物的集群行为,都离不开精心设计的运动AI脚本,Unity作为主流游戏引擎,提供了NavMesh导航系统、物理引擎等强大工具,结合C#脚本编程,开发者可以实现从简单到复杂的各类智能体运动行为,本文将系统讲解Unity中智能体运动AI脚本的设计思路与实现方法。
智能体运动的基本概念
智能体是指能够感知环境并自主做出决策的虚拟实体,一个完整的运动AI系统通常包含三个层次:
- 感知层:获取环境信息,如玩家位置、障碍物、路径点等
- 决策层:根据感知信息决定行为,如追击、逃跑、巡逻
- 执行层:将决策转化为具体的位移和旋转
在Unity中,执行层的运动实现主要有两种方式:Transform直接控制和基于物理的控制(Rigidbody或CharacterController),前者简单直接但缺乏物理交互,后者更加真实自然。
基础移动脚本实现
1 朝向目标的追踪移动
最基础的追踪行为是让智能体朝目标位置移动并平滑转向:
using UnityEngine;
public class SimpleChaseAgent : MonoBehaviour
{
public Transform target;
public float moveSpeed = 5f;
public float rotateSpeed = 10f;
public float stopDistance = 1.5f;
void Update()
{
if (target == null) return;
Vector3 direction = target.position - transform.position;
direction.y = 0; // 忽略高度差
float distance = direction.magnitude;
if (distance <= stopDistance) return;
// 平滑旋转朝向目标
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(
transform.rotation,
targetRotation,
rotateSpeed * Time.deltaTime
);
// 沿前方移动
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}
}
这种实现方式简单高效,但智能体会被障碍物阻挡,无法自动绕行。
2 基于物理的运动控制
使用Rigidbody可以获得更真实的运动效果:
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PhysicsAgent : MonoBehaviour
{
public float moveForce = 20f;
public float maxSpeed = 6f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
public void MoveTowards(Vector3 targetPosition)
{
Vector3 direction = (targetPosition - transform.position).normalized;
rb.AddForce(direction * moveForce);
// 限制最大速度
if (rb.velocity.magnitude > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed;
}
}
}
NavMesh导航系统:智能寻路的核心
对于复杂场景,Unity的NavMesh系统是智能体寻路的首选方案,使用前需要先对场景进行烘焙(Window → AI → Navigation),然后为智能体添加NavMeshAgent组件。
1 基础导航脚本
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class NavigationAgent : MonoBehaviour
{
private NavMeshAgent agent;
public Transform target;
void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.speed = 4f;
agent.angularSpeed = 120f;
agent.stoppingDistance = 1f;
}
void Update()
{
if (target != null)
{
agent.SetDestination(target.position);
}
}
}
2 巡逻行为实现
巡逻是游戏中常见的AI行为,通过路径点(Waypoints)系统实现:
using UnityEngine;
using UnityEngine.AI;
public class PatrolAgent : MonoBehaviour
{
public Transform[] waypoints;
public float waitTime = 2f;
private NavMeshAgent agent;
private int currentIndex = 0;
private float waitTimer = 0f;
private bool isWaiting = false;
void Start()
{
agent = GetComponent<NavMeshAgent>();
GoToNextWaypoint();
}
void Update()
{
if (isWaiting)
{
waitTimer += Time.deltaTime;
if (waitTimer >= waitTime)
{
isWaiting = false;
GoToNextWaypoint();
}
return;
}
// 到达路径点后开始等待
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
isWaiting = true;
waitTimer = 0f;
}
}
void GoToNextWaypoint()
{
if (waypoints.Length == 0) return;
agent.SetDestination(waypoints[currentIndex].position);
currentIndex = (currentIndex + 1) % waypoints.Length;
}
}
有限状态机:让运动更智能
真实的游戏AI需要多种行为切换,有限状态机(FSM)是管理这些状态的经典方案,下面实现一个具备“巡逻—追击—返回”三种状态的敌人AI:
using UnityEngine;
using UnityEngine.AI;
public class EnemyFSM : MonoBehaviour
{
public enum State { Patrol, Chase, Return }
public State currentState = State.Patrol;
public Transform player;
public float detectRange = 10f;
public float loseRange = 15f;
public Transform[] patrolPoints;
private NavMeshAgent agent;
private Vector3 startPosition;
private int patrolIndex = 0;
void Start()
{
agent = GetComponent<NavMeshAgent>();
startPosition = transform.position;
}
void Update()
{
float distanceToPlayer = Vector3.Distance(
transform.position, player.position
);
switch (currentState)
{
case State.Patrol:
Patrol();
if (distanceToPlayer < detectRange)
SwitchState(State.Chase);
break;
case State.Chase:
agent.SetDestination(player.position);
if (distanceToPlayer > loseRange)
SwitchState(State.Return);
break;
case State.Return:
agent.SetDestination(startPosition);
if (!agent.pathPending && agent.remainingDistance < 0.5f)
SwitchState(State.Patrol);
if (distanceToPlayer < detectRange)
SwitchState(State.Chase);
break;
}
}
void Patrol()
{
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
agent.SetDestination(patrolPoints[patrolIndex].position);
patrolIndex = (patrolIndex + 1) % patrolPoints.Length;
}
}
void SwitchState(State newState)
{
currentState = newState;
Debug.Log("切换状态: " + newState);
}
}
转向行为:更自然的群体运动
对于鸟群、鱼群等群体智能体,Craig Reynolds提出的转向行为(Steering Behaviors)算法能产生非常自然的效果,其核心包含三条规则:
- 分离(Separation):避免与邻近个体拥挤
- 对齐(Alignment):与邻近个体保持方向一致
- 聚合(Cohesion):向群体中心靠拢
using UnityEngine;
using System.Collections.Generic;
public class FlockAgent : MonoBehaviour
{
public float speed = 4f;
public float neighborRadius = 5f;
public float separationRadius = 2f;
[Range(0, 1)] public float separationWeight = 0.5f;
[Range(0, 1)] public float 文章版权声明:除非注明,否则均为新文化在线原创文章,转载或复制请以超链接形式并注明出处。
推荐阅读