Skip to content

Instantly share code, notes, and snippets.

@aleksandr-vin
Created March 31, 2022 14:33
Show Gist options
  • Save aleksandr-vin/67fc4dfd4263f90e11d336c7814db025 to your computer and use it in GitHub Desktop.
Save aleksandr-vin/67fc4dfd4263f90e11d336c7814db025 to your computer and use it in GitHub Desktop.
Unity script to control LERP move of a GameObject through checkpoints
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Class <c>MoveController</c> controls movement of GameObject via existing GameObjects that have tag 'CheckPoint'.
/// Speed is controlled via 'lerpSpeed'.
/// </summary>
public class MoveController : MonoBehaviour
{
public float lerpSpeed;
private GameObject[] checkPoints;
private IEnumerator coroutine;
// Start is called before the first frame update
void Start()
{
checkPoints = GameObject.FindGameObjectsWithTag("CheckPoint");
if (checkPoints.Length > 0)
{
coroutine = MoveToNext(this.transform.position, checkPoints);
StartCoroutine(coroutine);
}
}
IEnumerator MoveToNext(Vector3 start, GameObject[] destinations)
{
float time = 0;
Vector3 next = destinations[0].transform.position;
while (time < 1)
{
this.transform.position = Vector3.Lerp(start, next, time);
time += Time.deltaTime * lerpSpeed;
Debug.LogWarning(time);
yield return null;
}
List<GameObject> lst = new List<GameObject>(destinations);
lst.Add(destinations[0]);
lst.RemoveAt(0);
coroutine = MoveToNext(this.transform.position, lst.ToArray());
StartCoroutine(coroutine);
}
// Update is called once per frame
void FixedUpdate()
{
GameObject[] currentCheckPoints = GameObject.FindGameObjectsWithTag("CheckPoint");
if (currentCheckPoints.Length != checkPoints.Length)
{
StopCoroutine(coroutine);
checkPoints = currentCheckPoints;
coroutine = MoveToNext(this.transform.position, checkPoints);
StartCoroutine(coroutine);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment