用协程实现移动平台
创建空对象MovePlatform,里面添加平台和两个移动点
public class MovePlatform : MonoBehaviour
{
//不使用update,在start中用协程做一个会在两点之间移动的平台
public Transform movePlatform;
public Transform p1, p2;
private void Start()
{
movePlatform.position = p1.position;
StartCoroutine(Moving());
}
IEnumerator Moving()
{
float t = 0f;
int dir = 1;
while (true)
{
t += dir * 0.3f * Time.deltaTime; //累计一个比值 用于在两点间移动
//使t在0~1之间
if (t >= 1f)
dir = -1;
if(t <= 0)
{
dir = 1;
}
movePlatform.transform.position = Vector3.Lerp(p1.position, p2.position, t);
yield return null;
}
}
}
Mathf.Lerp(float a, float b, float t)
:线性插值(linear interpolation)
简单来说就是得到一个a和b之间的数,当t=0时为a,t=1时为b,t在0到1之间时为从a到b相应比例的值。
比如:Mathf.Lerp(50,100,0.5)等于75