主要参考这个博主的代码
根据我的需求:
1.我是3D游戏,而博主的代码是针对2D游戏。
2.希望可以在游戏界面上增加一个slider,以实时调节物体移动速度。
我进行了修改,修改后的代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineMove : MonoBehaviour
{
public GameObject line; // 线路组,包含所有路点的父对象
public Transform[] line_array; // 所有路点位置的数组
[Range(0, 50)]
public float speed; // 移动速度
private Rigidbody body; // 刚体组件,用于3D物理移动
[Range(0, 10)]
public float point_waittime; // 不在此示例中使用,可忽略或根据需要实现等待逻辑
[Range(0, 10)]
public float point_distance; // 距离路点的位置容忍差
private int index; // 当前目标路点的索引
public void SetSpeed(float newSpeed)
{
speed = newSpeed;
}
// Start is called before the first frame update
void Start()
{
index = 0;
body = GetComponent<Rigidbody>(); // 获取3D刚体组件
line_array = new Transform[line.transform.childCount]; // 初始化路点数组
for (int i = 0; i < line.transform.childCount; i++)
{
line_array[i] = line.transform.GetChild(i); // 获取每个子节点(路点)的Transform组件
}
}
// Update is called once per frame
void Update()
{
Move_line0();
}
private float Get_Distance(Transform point) // 获取物体和路点的距离
{
return Vector3.Distance(transform.position, point.position);
}
void Move_line0() // 移动方式-0
{
if (Get_Distance(line_array[index]) <= point_distance)
{
index = (index + 1) % line_array.Length; // 循环到下一个路点
}
Move();
}
void Move() // 朝向目标移动
{
Vector3 direction = line_array[index].position - transform.position; // 计算方向向量
float distanceThisFrame = speed * Time.deltaTime; // 计算这一帧应该移动的距离
Vector3 movement = direction.normalized * distanceThisFrame; // 根据方向和距离计算移动量
body.MovePosition(transform.position + movement); // 移动刚体到新的位置
}
}
大功告成。
unity用slider实时调控速度