[Unity] Dreamteck Splines实现沿路径移动功能
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                
using UnityEngine;
using Dreamteck.Splines;
 
public class AlongSplineMovement : MonoBehaviour {
    public Spline spline;
    public float speed = 1f;
    public bool isMoving = true;
 
    private float currentTime = 0f;
    private bool reachedEnd = false;
 
    void Update() {
        if (isMoving && !reachedEnd) {
            currentTime += Time.deltaTime * speed;
            float moveDistance = speed * Time.deltaTime;
            int targetIndex = spline.GetClosestPointIndex(transform.position, moveDistance);
            Vector3 targetPoint = spline.GetPoint(targetIndex);
            transform.position = Vector3.MoveTowards(transform.position, targetPoint, moveDistance);
 
            if (targetIndex == spline.GetPointCount() - 1) {
                reachedEnd = true;
                // 可以在这里添加到达终点的回调或其他逻辑
            }
        }
    }
}这段代码使用了Dreamteck Splines插件中的功能,使得物体沿着spline移动。其中currentTime用于追踪当前的时间,isMoving控制物体是否在移动,reachedEnd用于检测是否已经到达了spline的末端。在Update方法中,根据当前的时间、速度和spline的点信息来计算物体下一个应该到达的位置,并且更新其transform的位置。如果物体到达了spline的末端,reachedEnd会被设置为true,这时可以添加相应的回调或者其他逻辑。
评论已关闭