沿着引导的路径穿越
本文关键字:路径 穿越 | 更新日期: 2023-09-27 18:12:34
var distancesquared = (transform.position - currentpath.Current.position).sqrMagnitude;
if (distancesquared < 0.1f * 0.1f)
currentpath.MoveNext ();
我已经创建了一条路径,使用一个统一的变换数组,现在如果我不使用上面的If语句,只做currentpath.MoveNext()
,它只是沿着第一对点遍历,而不走一个以上来完成路径,请问这个If语句与遍历路径的相关关系是什么?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class followpath : MonoBehaviour {
public enum followtype
{
movetowards,
lerp
}
public followtype type = followtype.movetowards;
public Pathdefinition path;
public float speed = 1;
public float maxdistancetodo = 0.1f;
private IEnumerator<Transform> currentpath;
public void Start()
{
if (path == null)
{
Debug.LogError ("path can not be null", gameObject);
return;
}
currentpath = path.getpathenumerator ();
currentpath.MoveNext ();
if (currentpath.Current == null)
return;
transform.position = currentpath.Current.position;
}
public void Update()
{
if (currentpath == null || currentpath.Current == null)
return;
if (type == followtype.movetowards)
transform.position = Vector3.MoveTowards (transform.position, currentpath.Current.position, Time.deltaTime * speed);
else if (type == followtype.lerp)
transform.position = Vector3.Lerp (transform.position, currentpath.Current.position, Time.deltaTime * speed);
var distancesquared = (transform.position - currentpath.Current.position).sqrMagnitude;
if (distancesquared < maxdistancetodo* maxdistancetodo)
currentpath.MoveNext ();
}
}
当你在update中添加代码时,它会每帧执行一次。
if语句在迭代到路径中的下一个目标点之前,检查你的对象是否离当前目标位置足够近。
如果没有if语句,每一帧都会导致路径上的下一站被加载到迭代器中。这发生在您的对象有机会接近其前一个目标之前。此外,由于帧发生得如此之快,这意味着整个路径在不到一秒的时间内迭代,并且对象在设法移动很远之前就停止了移动。