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; } } } }
使用步骤:
- 在场景中创建四个空对象,分别放在正方形的四个顶点位置,调整好坐标
- 将这四个空对象按路径顺序(比如顺时针:左上→右上→右下→左下)拖拽到脚本的
squareWaypoints数组中(在Inspector面板操作) - 将脚本挂载到你要移动的Sprite对象上
- 运行游戏,点击鼠标左键启动移动,再次点击暂停
内容的提问来源于stack exchange,提问作者Vivek
相关产品推荐
相关产品推荐

