76 lines
1.9 KiB
C#
76 lines
1.9 KiB
C#
|
using UnityEngine;
|
||
|
|
||
|
public class LapTime : MonoBehaviour
|
||
|
{
|
||
|
public CheckPoint finishLine;
|
||
|
public CheckPoint checkPoint1;
|
||
|
public CheckPoint checkPoint2;
|
||
|
public CheckPoint checkPoint3;
|
||
|
|
||
|
private float _startTime = -1;
|
||
|
private float _checkPoint1Time;
|
||
|
private float _checkPoint2Time;
|
||
|
private float _checkPoint3Time;
|
||
|
private float _finishTime;
|
||
|
private float _bestTime;
|
||
|
|
||
|
public string GetTimeString()
|
||
|
{
|
||
|
return
|
||
|
$"Sector 1: {_checkPoint1Time:F}\nSector 2: {_checkPoint2Time:F}\nSector 3: {_checkPoint3Time:F}\nLast Lap Time: {_finishTime:F}\nBest Lap: {_bestTime:F}";
|
||
|
}
|
||
|
|
||
|
// Start is called before the first frame update
|
||
|
private void Start()
|
||
|
{
|
||
|
finishLine.CarPassed += FinishedLine;
|
||
|
checkPoint1.CarPassed += CheckPoint1Passed;
|
||
|
checkPoint2.CarPassed += CheckPoint2Passed;
|
||
|
checkPoint3.CarPassed += CheckPoint3Passed;
|
||
|
_bestTime = float.MaxValue;
|
||
|
_finishTime = float.MaxValue;
|
||
|
}
|
||
|
|
||
|
private void CheckPoint1Passed()
|
||
|
{
|
||
|
_checkPoint1Time = Time.time - _startTime;
|
||
|
}
|
||
|
|
||
|
private void CheckPoint2Passed()
|
||
|
{
|
||
|
_checkPoint2Time = Time.time - _startTime - _checkPoint1Time;
|
||
|
}
|
||
|
|
||
|
private void CheckPoint3Passed()
|
||
|
{
|
||
|
_checkPoint3Time = Time.time - _startTime - _checkPoint2Time - _checkPoint1Time;
|
||
|
}
|
||
|
|
||
|
private void ResetTimers()
|
||
|
{
|
||
|
_startTime = Time.time;
|
||
|
_checkPoint1Time = 0;
|
||
|
_checkPoint2Time = 0;
|
||
|
_checkPoint3Time = 0;
|
||
|
if (_finishTime < _bestTime)
|
||
|
{
|
||
|
_bestTime = _finishTime;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private void FinishedLine()
|
||
|
{
|
||
|
// make sure we didn't skip a checkpoint.
|
||
|
if (_checkPoint1Time > 0 && _checkPoint2Time > 0 && _checkPoint3Time > 0)
|
||
|
{
|
||
|
// we finished
|
||
|
_finishTime = Time.time - _startTime;
|
||
|
ResetTimers();
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
ResetTimers();
|
||
|
}
|
||
|
}
|
||
|
}
|