Как создать систему движения объектов по принципу эстафеты в C#?
Нужно создать систему из нескольких объектов, которые двигаются как бегуны на эстафете: бежит только один, пока не добегает до другого. Если дистанция до следующего объекта становится меньше passDistance, объект перестаёт быть «бегуном», им становится следующий объект. И так по кругу.
Текущий код:
public class Runners : MonoBehaviour
{
[SerializeField] Transform[] _runners;
[SerializeField] float _speed;
private Transform _currentRunner;
private Transform _nextRunner;
private Vector3 _currentRunnerPosition;
private Vector3 _nextRunnerPosition;
int _runnerIndex;
float _distance;
float _passDistance = 0.01f;
void Start()
{
_currentRunnerPosition = _runners[0].position;
_runnerIndex = 0;
_nextRunnerPosition = _runners[_runnerIndex++].position;
}
void Update()
{
_currentRunnerPosition = Vector3.MoveTowards(_currentRunnerPosition, _nextRunnerPosition, Time.deltaTime * _speed);
ChangeRunner();
}
void ChangeRunner()
{
_distance = Vector3.Distance(_nextRunnerPosition, _currentRunnerPosition);
if (_distance <= _passDistance)
{
_runnerIndex++;
if (_runnerIndex >= _runners.Length)
{
_runnerIndex = 0;
}
_nextRunner = _runners[_runnerIndex];
_currentRunner = _nextRunner;
_nextRunnerPosition = _runners[_runnerIndex++].position;
_currentRunner.LookAt(_nextRunner);
}
}
}
Источник: Stack Overflow на русском