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

Unity 2D敌人左右巡逻:首次左移行程过长问题求助

敌人巡逻首次移动超范围问题修复

问题原因

你的问题出在初始位置未做边界限制,以及原边界判断逻辑存在误差:

  • 若敌人初始位置不在[minX, maxX]区间内(比如偏右过多),原代码的翻转触发条件minX + speed * Time.deltaTime阈值高于实际左边界,会导致敌人持续左移远超预期范围,直到满足条件才翻转。
  • 原逻辑没有强制将敌人初始位置拉回巡逻区间,直接导致首次移动失控。

修复方案

调整边界判断逻辑,触达边界时强制修正位置,同时初始化时确保敌人处于巡逻范围内:

using UnityEngine;

public class EnemyPatrol : MonoBehaviour
{
    public float speed = 1f; 
    public float maxX = 1f;
    public float minX = -1f; 

    private Rigidbody2D rb;
    private bool movingRight = false; 

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        // 初始化时将敌人位置限制在巡逻范围内
        float clampedX = Mathf.Clamp(transform.position.x, minX, maxX);
        transform.position = new Vector3(clampedX, transform.position.y, transform.position.z);
    }

    void FixedUpdate()
    {
        if (movingRight)
        {
            if (transform.position.x >= maxX)
            {
                // 修正位置到右边界
                transform.position = new Vector3(maxX, transform.position.y, transform.position.z);
                Flip();
            }
            else
            {
                rb.velocity = new Vector2(speed, rb.velocity.y);
            }
        }
        else
        {
            if (transform.position.x <= minX)
            {
                // 修正位置到左边界
                transform.position = new Vector3(minX, transform.position.y, transform.position.z);
                Flip();
            }
            else
            {
                rb.velocity = new Vector2(-speed, rb.velocity.y);
            }
        }
    }

    void Flip()
    { 
        movingRight = !movingRight;
        Vector3 scale = transform.localScale;
        scale.x *= -1;
        transform.localScale = scale;
    }
}

关键修改点

  1. 初始位置修正:用Mathf.Clamp强制将敌人X坐标限制在巡逻区间内,确保移动从正确起点开始。
  2. 边界判断优化:直接以maxX/minX作为翻转触发条件,同时修正位置到边界,彻底避免因帧时间或速度误差导致的超范围移动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 18:44:53