I created a version of the movement script in the lecture using coroutines. I also made it an option so that when you give a new move instruction, you can complete the previous one instantly or keep moving.
For the move issue. To not make any assumptions about if the speed will not overstep our target. I made it so that if the step we want to take is bigger than the actual distance, then we just traverse the distance. Else our movement speed applies.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Unit : MonoBehaviour
{
#region Editor Variables
[SerializeField]
private float _speed = 4f;
#endregion
#region Variables
private IEnumerator _moveRoutine = null;
private Vector3 _targetPosition = default;
#endregion
#region Lifecycle
protected void Update()
{
if(Input.GetKeyDown(KeyCode.T))
{
Move(new Vector3(4, 0, 4));
}
}
#endregion
#region Public Methods
public void Move(Vector3 targetPosition, bool instantComplete = false)
{
StartMoveRoutine(targetPosition, instantComplete);
}
#endregion
#region Private Methods
private void StartMoveRoutine(Vector3 targetPosition, bool instantComplete)
{
EndMoveRoutine(instantComplete);
_targetPosition = targetPosition;
StartCoroutine(_moveRoutine = MoveRoutine());
}
private void EndMoveRoutine(bool complete)
{
if(_moveRoutine != null)
{
StopCoroutine(_moveRoutine);
_moveRoutine = null;
if(complete)
{
transform.position = _targetPosition;
}
}
}
private IEnumerator MoveRoutine()
{
bool isMoving = true;
while(isMoving)
{
Vector3 totalStep = _targetPosition - transform.position;
Vector3 step = totalStep.normalized * Time.deltaTime * _speed;
if(totalStep.magnitude <= step.magnitude)
{
step = totalStep;
isMoving = false;
}
transform.Translate(step);
yield return null;
}
EndMoveRoutine(true);
}
#endregion
}