50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using UnityEngine;
|
|
|
|
namespace Code.Gameplay
|
|
{
|
|
public class AICarController : MonoBehaviour
|
|
{
|
|
[SerializeField] public float speed = 15f;
|
|
[SerializeField] private float stoppingDistance = 2f;
|
|
[SerializeField] private float turnSpeed = 3f;
|
|
|
|
private Vector3[] _waypoints;
|
|
private int _currentWaypointIndex;
|
|
|
|
private bool _isStopped;
|
|
|
|
public void SetRoute(Vector3[] waypoints)
|
|
{
|
|
_waypoints = waypoints;
|
|
_currentWaypointIndex = 0;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (_waypoints == null || _waypoints.Length == 0 || _isStopped) return;
|
|
|
|
if (_currentWaypointIndex >= _waypoints.Length - 1)
|
|
{
|
|
var raceManager = FindFirstObjectByType<RaceManager>();
|
|
raceManager?.OnLoose();
|
|
_isStopped = true;
|
|
}
|
|
|
|
var target = _waypoints[_currentWaypointIndex];
|
|
var direction = target - transform.position;
|
|
|
|
if (direction.magnitude > 0.1f)
|
|
{
|
|
var targetRotation = Quaternion.LookRotation(direction, Vector3.up);
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
|
|
}
|
|
|
|
transform.Translate(Vector3.forward * (speed * Time.deltaTime), Space.Self);
|
|
|
|
if (direction.magnitude < stoppingDistance)
|
|
{
|
|
_currentWaypointIndex = (_currentWaypointIndex + 1) % _waypoints.Length;
|
|
}
|
|
}
|
|
}
|
|
} |