You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity AI车辆路点移动异常:后续路点移动过快求助

问题排查与解决方案

核心问题分析

  • 多协程叠加运行:原代码每切换路点就启动新协程,但前一个协程的while(true)无限循环并未终止,导致多个协程同时在每一帧修改车辆位置,移动速度被叠加(第二个路点时两个协程同时驱动,速度翻倍,后续路点速度持续叠加)。
  • 语法与逻辑错误:SparseUpdateSecond中的移动语句缺少MoveSpeed参数(transform.position += transform.forward * * Time.deltaTime;),且判断到达目标时错误引用了第一个路点Player而非当前路点Player2,触发条件混乱。

修正后的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AICar : MonoBehaviour
{
    // 用列表统一管理所有路点,便于扩展和维护
    public List<Transform> waypoints = new List<Transform>();
    public int moveSpeed = 5;
    [SerializeField] private int triggerDistance = 10; // 到达此距离时准备切换路点
    [SerializeField] private int stopDistance = 5; // 到达此距离时停止向当前路点移动

    private void Start()
    {
        StartCoroutine(MoveThroughWaypoints());
    }

    private IEnumerator MoveThroughWaypoints()
    {
        // 遍历所有路点
        foreach (var waypoint in waypoints)
        {
            // 未到达当前路点停止距离时,持续移动
            while (Vector3.Distance(transform.position, waypoint.position) > stopDistance)
            {
                transform.LookAt(waypoint);
                transform.position += transform.forward * moveSpeed * Time.deltaTime;

                yield return null; // 等待下一帧
            }

            // 可选:到达路点后停留一段时间,不需要可删除
            yield return new WaitForSeconds(0.5f);
        }

        // 所有路点完成后的逻辑(比如循环回到第一个路点)
        // StartCoroutine(MoveThroughWaypoints());
    }
}

关键改进说明

  • 路点列表化:用List<Transform>替代多个单独的Transform变量,新增路点只需在Inspector中添加,无需修改代码,提升可维护性。
  • 单协程管理:单个协程按顺序处理所有路点,完成当前路点后才进入下一个,彻底避免多协程叠加导致的速度异常。
  • 逻辑简化:明确区分触发路点切换的距离和停止移动的距离,移除原代码中冗余且易出错的双重距离判断。
  • 语法修复:补全移动语句缺失的参数,修正目标路点的判断逻辑。

内容的提问来源于stack exchange,提问作者Moritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:40:35