来回移动GameObject

我有一个对象,我想要移动到A点,当它到达A点时它应该移动到B点。当它到达B点时它应该移回A点。

我以为我可以使用Vector3.Lerp

void Update() { transform.position = Vector3.Lerp(pointA, pointB, speed * Time.deltaTime); } 

但是我怎么能回去呢? 是否有一种优雅的方式来实现这一目标? 显然我需要这样的2 Lerps:

 void Update() { transform.position = Vector3.Lerp(pointA, pointB, speed * Time.deltaTime); // Move up transform.position = Vector3.Lerp(pointB, pointA, speed * Time.deltaTime); // Move down } 

有人可以帮帮我吗?

有很多方法可以做到这一点,但Mathf.PingPong是最简单,最简单的方法。 使用Mathf.PingPong获取01之间的数字,然后将该值传递给Vector3.Lerp 。 而已。

Mathf.PingPong将自动返回将在01之间来回移动的值。 阅读链接文档以获取更多信息。

 public float speed = 1.19f; Vector3 pointA; Vector3 pointB; void Start() { pointA = new Vector3(0, 0, 0); pointB = new Vector3(5, 0, 0); } void Update() { //PingPong between 0 and 1 float time = Mathf.PingPong(Time.time * speed, 1); transform.position = Vector3.Lerp(pointA, pointB, time); }