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

Unity开发疑问:为何我的精灵无法移动至第一个路点以外?

排查精灵无法前往后续路点的问题

嗨,看你贴的代码片段,问题一目了然——Move()方法里的到达路点后切换索引的逻辑没写完,这就是僵尸卡在第一个路点的核心原因:走到第一个路点后,程序根本不知道要切换到下一个路点,自然就原地不动了。

核心问题拆解

你只写了if (transform....就中断了,完整逻辑需要包含两个关键步骤:

  1. 检测精灵是否已经到达当前路点(要注意浮点精度问题,别直接用==判断位置)
  2. 到达后将路点索引切换到下一个,并且处理循环/停止的逻辑

修复后的完整代码

我帮你补全了缺失的逻辑,还加了一些鲁棒性处理(比如判断路点数组是否为空),直接替换你的脚本就行:

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

public class ZombieControl : MonoBehaviour {
    [SerializeField] Transform[] waypoints;
    [SerializeField] float moveSpeed = 2f;
    [SerializeField] float waypointThreshold = 0.1f; // 解决浮点精度问题的阈值
    int wayPointIndex = 0;

    void Start() {
        // 避免路点为空时报错
        if (waypoints.Length > 0) {
            transform.position = waypoints[wayPointIndex].position;
        }
    }

    void Update() {
        Move();
    }

    void Move() {
        // 路点数组为空直接返回,防止空引用错误
        if (waypoints == null || waypoints.Length == 0) return;

        // 向当前路点移动
        transform.position = Vector2.MoveTowards(transform.position, waypoints[wayPointIndex].position, moveSpeed * Time.deltaTime);

        // 检测是否到达路点附近
        float distanceToWaypoint = Vector2.Distance(transform.position, waypoints[wayPointIndex].position);
        if (distanceToWaypoint <= waypointThreshold) {
            // 切换到下一个路点
            wayPointIndex++;
            // 循环移动:走到最后一个路点后回到第一个
            if (wayPointIndex >= waypoints.Length) {
                wayPointIndex = 0;
                // 如果不需要循环,改成 wayPointIndex = waypoints.Length - 1; 让僵尸停在最后一个路点
            }
        }
    }
}

额外注意事项

  • 一定要在Unity Inspector面板里给waypoints数组添加至少2个路点对象,并且调整好路点的顺序和位置
  • waypointThreshold的值可以根据你的精灵大小调整,比如精灵是1x1的话,0.1f足够,要是精灵很大可以适当调大
  • 如果不需要循环移动,把索引重置的逻辑改成停留在最后一个路点即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:36:03