UnityGameProjectsCode / Rise2Point0Game / Obstacles / MoveObstacle.cs
MoveObstacle.cs
Raw
using UnityEngine;

public class MoveObstacle : MonoBehaviour
{
    public float movementSpeed;
    public Transform startingPos;
    public Transform endingPos;
    private float startTime;
    private float journeyLength;

    private void Start()
    {
        startTime = Time.time;
        journeyLength = Vector3.Distance(startingPos.position, endingPos.position);
    }

    private void Update()
    {
        // Distance moved = time * speed.
        float distCovered = (Time.time - startTime) * movementSpeed;

        // Fraction of journey completed = current distance divided by total distance.
        float fracJourney = distCovered / journeyLength;

        // Set our position as a fraction of the distance between the markers.
        transform.position = Vector3.Lerp(startingPos.position, endingPos.position, fracJourney);

        if (transform.position == endingPos.position)
        {
            Transform tempTransform = startingPos;
            startingPos = endingPos;
            endingPos = tempTransform;
            startTime = Time.time;
        }
    }
}