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

Unity 2D俯视角游戏:消除图像移动至巡逻点时的旋转问题

解决巡逻切换点时物体不旋转的问题

嘿,我懂你遇到的问题了——你想让巡逻的物体切换到下一个目标点时,保持当前的旋转方向不改变,对吧?之前尝试修复没成功没关系,咱们来捋一捋代码里的问题,然后搞定它!

问题出在哪?

你原来的代码里,Update函数每帧都在计算朝向当前巡逻点的旋转角度,所以每次切换到新的巡逻点,物体就会自动转向新目标,这就是导致旋转的核心原因。咱们要做的就是让旋转逻辑只在必要的时候触发,而不是每帧都更新。

修复后的代码

[SerializeField] private Transform[] patrolPoints;
Transform currentPatrolPoint;
int currentPatrolIndex;

protected override void Start() {
    currentPatrolIndex = 0;
    currentPatrolPoint = patrolPoints[currentPatrolIndex];
    // 初始化时只设置一次朝向第一个巡逻点的方向
    SetPatrolDirection();
    base.Start();
}

protected override void Update() {
    // 保持当前方向持续移动
    transform.Translate(Vector3.up * Time.deltaTime * MySpeed);

    if (Vector3.Distance(transform.position, currentPatrolPoint.position) < 0.1f) {
        // 切换到下一个巡逻点
        currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length;
        currentPatrolPoint = patrolPoints[currentPatrolIndex];
        
        // 重点:注释掉下面这行,切换点时就不会重新调整方向(也就是不旋转)
        // SetPatrolDirection();
    }
}

// 单独封装的方向设置方法,按需调用
private void SetPatrolDirection() {
    Vector3 patrolPointDirection = currentPatrolPoint.position - transform.position;
    float angle = Mathf.Atan2(patrolPointDirection.y, patrolPointDirection.x) * Mathf.Rad2Deg - 90f;
    Quaternion targetRotation = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = targetRotation;
}

关键修改说明

  1. 把旋转逻辑抽成了SetPatrolDirection()独立方法,方便灵活控制触发时机
  2. 初始化时仅调用一次方向设置,让物体一开始朝向第一个巡逻点
  3. 最核心的调整:在切换巡逻点的代码块中,我注释掉了SetPatrolDirection()——这样物体到达巡逻点切换目标时,不会重新计算方向,也就保持了当前旋转继续移动
  4. 顺便把巡逻点索引切换的逻辑简化成了取模运算,代码更简洁

这样修改后,物体就会保持初始(或你最后一次设置的)方向持续移动,切换巡逻点时再也不会突然旋转啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:08:47