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

Unity新手求助:实现鼠标点击时2D物体沿正方形路径移动

解决2D Sprite沿正方形路径移动的问题

先指出你原代码里的核心问题:

  • target2从未初始化,直接访问会报空引用错误
  • hero == target1是比较两个Transform的引用地址,除非两个对象是同一个,否则这个判断永远不成立,应该判断对象是否到达目标位置
  • MoveTowards的速度参数错误,应该是speed * Time.deltaTime,你漏了乘speed,而且语法上多了个多余的星号
  • 没有定义正方形路径的所有关键点,只设置了两个目标,没法完成完整的正方形路径移动

下面是修正后的完整代码,实现鼠标点击一次,Sprite就沿正方形路径循环移动的功能:

using UnityEngine;

public class MouseToMove : MonoBehaviour
{
    // 移动速度
    public float speed = 5.0f;
    // 正方形路径的四个顶点(在Inspector面板拖拽赋值)
    public Transform[] squareWaypoints;
    // 当前要移动到的目标点索引
    private int currentWaypointIndex = 0;
    // 是否正在移动
    private bool isMoving = false;

    void Update()
    {
        // 鼠标左键点击,切换移动/暂停状态
        if (Input.GetMouseButtonDown(0))
        {
            isMoving = !isMoving;
            // 第一次点击直接启动移动
            if (currentWaypointIndex == 0)
            {
                isMoving = true;
            }
        }

        if (isMoving)
        {
            // 向当前目标点移动
            transform.position = Vector2.MoveTowards(transform.position, squareWaypoints[currentWaypointIndex].position, speed * Time.deltaTime);

            // 检查是否到达当前目标点(距离小于0.1判定为到达,避免浮点数精度问题)
            if (Vector2.Distance(transform.position, squareWaypoints[currentWaypointIndex].position) < 0.1f)
            {
                // 切换到下一个目标点,循环回到第一个点
                currentWaypointIndex = (currentWaypointIndex + 1) % squareWaypoints.Length;
            }
        }
    }
}

使用步骤:

  1. 在场景中创建四个空对象,分别放在正方形的四个顶点位置,调整好坐标
  2. 将这四个空对象按路径顺序(比如顺时针:左上→右上→右下→左下)拖拽到脚本的squareWaypoints数组中(在Inspector面板操作)
  3. 将脚本挂载到你要移动的Sprite对象上
  4. 运行游戏,点击鼠标左键启动移动,再次点击暂停

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:20:31