【代码分享】Unity3D中物体沿直线轨迹运动并实时调节速度

主要参考这个博主的代码

Unity实现敌人沿着指定路线移动_unity 让物体按照路径点移动-CSDN博客

根据我的需求:

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实时调控速度

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值