Move GameObject back and forth

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

Leave a Comment