2017-03-24 81 views
0

我得到一个对象,我想要移动到点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 
} 

有人可以帮我吗?

回答

4

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

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

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); 
} 
+1

哇,帮助!非常感谢。 – Question3r