CSharp · Console
using System.Linq;
using UnityEngine;
using UnityEditor;
public class WaypointPath : MonoBehaviour
{
public Transform GetWaypoint(int waypointIndex)
{
return transform.GetChild(waypointIndex);
}
public int GetNextWaypointIndex(int currentWaypointIndex)
{
int nextWaypointIndex = currentWaypointIndex + 1;
if (nextWaypointIndex == transform.childCount)
{
nextWaypointIndex = 0;
}
return nextWaypointIndex;
}
private void OnDrawGizmos()
{
if (IsWaypointSelected())
{
DrawWaypointGizmos();
}
}
public void DrawWaypointGizmos()
{
for (int waypointIndex = 0; waypointIndex < transform.childCount; waypointIndex++)
{
var waypoint = GetWaypoint(waypointIndex);
Gizmos.color = Color.cyan;
Gizmos.DrawSphere(waypoint.position, 0.2f);
int nextWaypointIndex = GetNextWaypointIndex(waypointIndex);
var nextWaypoint = GetWaypoint(nextWaypointIndex);
Gizmos.color = Color.yellow;
Gizmos.DrawLine(waypoint.position, nextWaypoint.position);
}
}
private bool IsWaypointSelected()
{
if (Selection.transforms.Contains(transform))
{
return true;
}
foreach (Transform child in transform)
{
if (Selection.transforms.Contains(child))
{
return true;
}
}
return false;
}
}
// ----------------------------------------------------------------------------------
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
[SerializeField]
private WaypointPath _waypointPath;
[SerializeField]
private float _speed;
private int _targetWaypointIndex;
private Transform _previousWaypoint;
private Transform _targetWaypoint;
private float _timeToWaypoint;
private float _elapsedTime;
private void OnDrawGizmosSelected()
{
_waypointPath.DrawWaypointGizmos();
}
// Start is called before the first frame update
void Start()
{
TargetNextWaypoint();
}
void FixedUpdate()
{
_elapsedTime += Time.deltaTime;
float elapsedPercentage = _elapsedTime / _timeToWaypoint;
elapsedPercentage = Mathf.SmoothStep(0, 1, elapsedPercentage);
transform.position = Vector3.Lerp(_previousWaypoint.position, _targetWaypoint.position, elapsedPercentage);
transform.rotation = Quaternion.Lerp(_previousWaypoint.rotation, _targetWaypoint.rotation, elapsedPercentage);
if (elapsedPercentage >= 1)
{
TargetNextWaypoint();
}
}
private void TargetNextWaypoint()
{
_previousWaypoint = _waypointPath.GetWaypoint(_targetWaypointIndex);
_targetWaypointIndex = _waypointPath.GetNextWaypointIndex(_targetWaypointIndex);
_targetWaypoint = _waypointPath.GetWaypoint(_targetWaypointIndex);
_elapsedTime = 0;
float distanceToWaypoint = Vector3.Distance(_previousWaypoint.position, _targetWaypoint.position);
_timeToWaypoint = distanceToWaypoint / _speed;
}
private void OnTriggerEnter(Collider other)
{
other.transform.SetParent(transform);
}
private void OnTriggerExit(Collider other)
{
other.transform.SetParent(null);
}
}