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?
Thanks!
Answer by Scribe · Mar 22, 2018 at 09:25 PM
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);
I did some playing around with this and the last number is how much of the path the object completes.
For example, if it is changed to 0.5 it will complete half the path, and if it is changed to 2 it tries to complete double the path length (but gets stopped by a wall, so stops for a while until it's time to move back).
You must call it as follow ins$$anonymous$$d :
$$anonymous$$athf.PingPong(Time.time / duration, 1);
Where duration
can be your public variable
Oops! quite right, I've updated my answer, hope that's okay :)