Unity3D物体从自身起点作一个长方形的轨迹不断循环移动的脚本
时间: 2024-10-12 10:16:28 浏览: 66
在Unity3D中,为了创建一个物体沿长方形路径循环移动的脚本,你可以使用`Vector3`类来表示方向,`Transform`类来操作位置,并结合`Coroutine`来实现动画效果。这里是一个基本的示例脚本:
```csharp
using UnityEngine;
using System.Collections;
public class RectangularPath : MonoBehaviour
{
// 长方形路径的两个顶点坐标
public Vector3[] pathPoints = new Vector3[4] {
new Vector3(0, 0, 0), // 起点
new Vector3(Screen.width / 2, 0, 0), // 点A
new Vector3(Screen.width, 0, 0), // 点B
new Vector3(Screen.width / 2, Screen.height, 0) // 点C (回环到起点)
};
// 移动速度和旋转速度
public float speed = 5f;
public float rotationSpeed = 90f;
private int currentPointIndex = 0;
void Update()
{
if (currentPointIndex == pathPoints.Length - 1) // 当到达终点时回到起点
currentPointIndex = 0;
// 更新当前位置
transform.position = pathPoints[currentPointIndex];
// 每次移动一小段距离
transform.Translate(Vector3.forward * speed * Time.deltaTime);
// 如果需要绕着轴旋转,可以这样添加
// transform.Rotate(new Vector3(0, rotationSpeed * Time.deltaTime, 0), Space.Self);
// 更新当前点索引
currentPointIndex++;
}
}
```
在这个脚本中,物体将沿着定义好的四个点(起点、AB线段、BC线段、回转到起点的线段)无限循环移动。你可以通过`pathPoints`数组调整路径,`speed`设置移动速度,`rotationSpeed`控制物体的旋转。
阅读全文
相关推荐











