Files
spacerace/Assets/Src/UI/TimingUI.cs
T
2023-08-01 22:45:20 +10:00

109 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
public class TimingUI : MonoBehaviour {
[SerializeField]
ShipControls ship;
Timing timing;
UIDocument uiDocument;
VisualElement recentLap;
VisualElement currentLap;
VisualElement sectors;
Label timer;
Label pb;
Label recentTime;
Label recentDiff;
void OnEnable() {
Init();
}
void Init() {
uiDocument = GetComponent<UIDocument>();
timing = GetComponent<Timing>();
recentLap = uiDocument.rootVisualElement.Q<VisualElement>("recentLap");
currentLap = uiDocument.rootVisualElement.Q<VisualElement>("currentLap");
sectors = uiDocument.rootVisualElement.Q<VisualElement>("sectors");
recentTime = uiDocument.rootVisualElement.Q<Label>("recentTime");
recentDiff = uiDocument.rootVisualElement.Q<Label>("recentDiff");
timer = uiDocument.rootVisualElement.Q<Label>("timer");
pb = uiDocument.rootVisualElement.Q<Label>("pb");
pb.text = "-";
recentLap.AddToClassList("hidden");
}
void FixedUpdate() {
if (timer == null) {
Debug.LogWarning("no timer");
Init();
return;
}
timer.text = $"{TimeSpan.FromSeconds(timing.lapTime):m\\:ss\\.fff}";
// clearly this is not ideal but idk atm
UpdateUI();
}
public void UpdateUI() {
if (sectors == null)
Debug.LogWarning("null sectors");
Lap pbLap = timing.PB();
if (pbLap != null)
pb.text = $"{pbLap.ToString()}";
sectors.Clear();
foreach (Sector sector in timing.sectors) {
Label l = timing.sectorTimes
.Where(s => s.Sector == sector.sector)
.Select(s => SectorLabel(s))
.DefaultIfEmpty(new Label("-"))
.Single();
sectors.Add(l);
}
}
public void ShowRecentLap(Lap lap) {
currentLap.AddToClassList("hidden");
recentLap.RemoveFromClassList("hidden");
recentTime.text = lap.ToString();
recentDiff.text = lap.ToString();
}
public void HideRecentLap() {
currentLap.RemoveFromClassList("hidden");
recentLap.AddToClassList("hidden");
}
Label SectorLabel(SectorTime s) {
double diff = timing.PBSectorDiff(s);
string sign = diff switch {
< 0 => "",
_ => "+",
};
SectorColour colour = diff switch {
< 0 => SectorColour.Green,
_ => SectorColour.Yellow,
};
Label l = new Label($"{sign}{diff:0.000}");
string colourClass = colour.ToString().ToLowerInvariant();
l.AddToClassList(colourClass);
return l;
}
}