Move GameObject back and forth
I got an Object that I want to move up to Point A and when it reaches Point A it should move to Point B. When it reaches Point B it should move back to Point A.
I thought I could use Vector3.Lerp for this
void Update()
{
transform.position = Vector3.Lerp(pointA, pointB, speed * Time.deltaTime);
}
But how can i move back then? Is there an elegant way to archieve this? Obviously I would need 2 Lerps like this way:
void Update()
{
transform.position = Vector3.Lerp(pointA, pointB, speed * Time.deltaTime); // Move up
transform.position = Vector3.Lerp(pointB, pointA, speed * Time.deltaTime); // Move down
}
Could someone help me out?
Solution 1:
There are many ways to do this but Mathf.PingPong
is the easiest and the simplest way to accomplish this. Use Mathf.PingPong
to get number between 0 and 1 then pass that value to Vector3.Lerp
. That's it.
Mathf.PingPong
will automatically return value will that will move back and forth between 0 and 1. Read the linked documentation for more info.
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);
}