using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace GrassCutter { /// /// The strip across the top of the screen: the eight points turn with your view, and the places worth finding your way /// back to sit on it with their distance along the ground. North is always the pole, and that is where the base stands. /// public class Compass { const float Width = 640f, Span = 130f; static readonly string[] Names = { Loc.N("N"), Loc.N("NE"), Loc.N("E"), Loc.N("SE"), Loc.N("S"), Loc.N("SW"), Loc.N("W"), Loc.N("NW") }; class Pin { public string name; public Vector3 dir; public Label label; public int station; } readonly VisualElement _strip; readonly Label[] _points = new Label[8]; readonly List _pins = new List(); public Compass(VisualElement root) { _strip = UIK.El("compass", root); for (int i = 0; i < 8; i++) _points[i] = UIK.Text(Loc.T(Names[i]), i % 2 == 0 ? "compass-point compass-main t-outline" : "compass-point t-outline", _strip); UIK.El("compass-mid", _strip); AddPin(Loc.T("BASE"), Vector3.up); for (int i = 1; i < Stations.Count; i++) AddPin(Stations.Names[i].ToUpper(Loc.Culture), Stations.Dir(i), i); } void AddPin(string name, Vector3 dir, int station = 0) => _pins.Add(new Pin { name = name, dir = dir, station = station, label = UIK.Text("", "compass-pin t-outline", _strip, false) }); /// Which way a line on the ground runs, in degrees clockwise from north. public static float Bearing(Vector3 up, Vector3 along) { var north = Vector3.ProjectOnPlane(Vector3.up, up); if (north.sqrMagnitude < 1e-4f) north = Vector3.ProjectOnPlane(Vector3.forward, up); return Vector3.SignedAngle(north, Vector3.ProjectOnPlane(along, up), up); } public static string Distance(float metres) => metres < 1000f ? Loc.F("{0:0} m", metres) : Loc.F("{0:0.0} km", metres / 1000f); void Set(VisualElement e, float bearing, float heading) { float off = Mathf.DeltaAngle(heading, bearing); bool on = Mathf.Abs(off) < Span * 0.5f; e.style.display = on ? DisplayStyle.Flex : DisplayStyle.None; if (on) e.style.left = Width * 0.5f + off / Span * Width; } public void Tick(PlayerAgent me, bool show) { _strip.style.display = show ? DisplayStyle.Flex : DisplayStyle.None; if (!show || !me) return; var up = Planet.Up(me.transform.position); float heading = Bearing(up, me.transform.forward); for (int i = 0; i < 8; i++) Set(_points[i], i * 45f, heading); var ts = TeamState.Instance; foreach (var p in _pins) { if (p.station > 0 && !(ts && ts.StationOpen(p.station))) { p.label.style.display = DisplayStyle.None; continue; } float metres = Mathf.Acos(Mathf.Clamp(Vector3.Dot(up, p.dir), -1f, 1f)) * Planet.Radius; // at the pin itself every bearing is as good as another float bearing = metres < 1f ? heading : Bearing(up, p.dir); p.label.text = p.name + " " + Distance(metres); Set(p.label, bearing, heading); } } } }