Lerp Confusion

Hi all,

I have this block of code:
using UnityEngine;
using System.Collections;

public class EnemyMove : MonoBehaviour
    public Transform startMarker;
    public Transform endMarker;

    void Update()
        transform.position = Vector3.Lerp(startMarker.position, endMarker.position, Mathf.PingPong(Time.time, 1));

Basically, it lerps an object from a start to an end marker, then goes back at the same speed and repeats. However, I want to attach it to multiple objects that will move at specific speeds. At the moment, all objects reach the start/end markers at the same time.

How would I change the duration of the movement for each object, preferably as a public variable so that I can edit it from the Unity editor?


The important bit for ‘speed’ is the last argument of Lerp, firstly it is important to know that when the third value is 0 we are at our start position, and at 1 we are at the end position:

Vector3.Lerp(positionA, positionB, 0) == positionA;
Vector3.Lerp(positionA, positionB, 1) == positionB;

Currently you have the third arg set to Mathf.PingPong(Time.time, 1) which means:

  • at 0 seconds it equals 0
  • at 1 second it equals 1
  • at 2 seconds it equals 0
  • at 3 seconds it equals 1 and so on.

This means we go there and back again once every two seconds. If you set it to Mathf.PingPong(Time.time/2.0, 1) we would go there and back again once every 4 seconds, i.e. twice as slowly!

as @Hellium says in the comments, extracting that to a variable means you can control how many seconds it takes to travel:

Mathf.PingPong(Time.time / duration, 1);