98 lines
2.6 KiB
C#
98 lines
2.6 KiB
C#
using System.Collections.Generic;
|
|
using Code.Example.Race.Racer.AI.ID;
|
|
using UnityEngine;
|
|
|
|
namespace Code.Example.Race.Racer.AI
|
|
{
|
|
public class AIRacerID : Racer
|
|
{
|
|
public override void SetData(RacerData data)
|
|
{
|
|
Data = data;
|
|
|
|
_velocity = Vector3.zero;
|
|
_steering = new Steering();
|
|
}
|
|
|
|
public override void Initialize(List<Transform> waypoints)
|
|
{
|
|
Waypoints = waypoints;
|
|
}
|
|
|
|
public override void NextWaypoint()
|
|
{
|
|
if(CurrentWaypointIndex >= Waypoints.Count) CurrentWaypointIndex = 0;
|
|
|
|
CurrentWaypointIndex++;
|
|
}
|
|
|
|
public override void StartRacer()
|
|
{
|
|
_running = true;
|
|
}
|
|
|
|
public override void StopRacer()
|
|
{
|
|
_running = false;
|
|
}
|
|
|
|
[SerializeField] private AgentBehaviour agent;
|
|
|
|
private float _orientation;
|
|
private float _rotation;
|
|
private Vector3 _velocity;
|
|
private Steering _steering;
|
|
private bool _running;
|
|
|
|
private float NormalizeAngle(float angle)
|
|
{
|
|
switch (angle)
|
|
{
|
|
case > 360.0f:
|
|
{
|
|
while (angle > 360.0f) angle -= 360.0f;
|
|
break;
|
|
}
|
|
case < 0.0f:
|
|
{
|
|
while (angle < 0.0f) angle += 360.0f;
|
|
break;
|
|
}
|
|
}
|
|
|
|
return angle;
|
|
}
|
|
public virtual void Update()
|
|
{
|
|
if (!_running) return;
|
|
|
|
var displacement = _velocity * Time.deltaTime;
|
|
_orientation += _rotation * Time.deltaTime;
|
|
_orientation = NormalizeAngle(_orientation);
|
|
|
|
transform.Translate(displacement, Space.World);
|
|
transform.Rotate(Vector3.up, _orientation);
|
|
}
|
|
public virtual void LateUpdate()
|
|
{
|
|
if (!_running) return;
|
|
|
|
_steering = agent.GetSteering(Waypoints[CurrentWaypointIndex]);
|
|
|
|
_velocity += _steering.linear * Time.deltaTime;
|
|
_rotation += _steering.angular * Time.deltaTime;
|
|
if (_velocity.magnitude > Data.speed)
|
|
{
|
|
_velocity = _velocity.normalized * Data.speed;
|
|
}
|
|
if (_steering.angular == 0.0f)
|
|
{
|
|
_rotation = 0.0f;
|
|
}
|
|
if (_steering.linear.sqrMagnitude == 0.0f)
|
|
{
|
|
_velocity = Vector3.zero;
|
|
}
|
|
}
|
|
}
|
|
} |