# 5. Compass Strip with Bearings
Part of [[Minimap, Compass and Waypoints]]. Previous: [[4. Full-Screen World Map with Pan and Zoom]]. Next: [[6. On-Screen Waypoints and Objective Markers]].
> [!warning] Code not compiled
> Written against the Unity 6000.5 Scripting API (`Mathf.DeltaAngle`, `IStyle.translate`, `VisualElement.visible`, `UsageHints.DynamicTransform`, `GeometryChangedEvent`, `Label`). **Not compiled or run in the Unity Editor.** A standalone Roslyn type-check of this series' C# against the Unity 6000.5.8f1 engine assemblies, URP 17.5.0 and Input System 1.20.0 passed with no errors (2026-11-26); the Editor, UXML/USS import, the `[UxmlElement]` source generator and runtime behaviour were **not** tested.
## 5.1 What the strip shows
```text
┌────────────────────────────────────────────────────────────────┐
│ | | | | | | ▼ | | | | | | │ ticks every 5°, major every 15°
│ W 285 300 NW │ 330 345 N │ labels on majors
│ ◆ ● │ markers by bearing
│ 120 m 42 m ▲ │ distance, elevation hint
└────────────────────────────────────────────────────────────────┘
```
- The strip spans `fieldOfView` degrees (180° is a common choice: everything in front of you). The centre is the current heading.
- A thing at bearing *b* sits at `x = centre + DeltaAngle(heading, b) × pixelsPerDegree`.
- `Mathf.DeltaAngle` returns the shortest signed difference in -180..180, so 350° → 10° is +20 and the strip wraps through north without special cases.
## 5.2 Where the heading comes from
| Game type | Heading source |
|---|---|
| First person | the camera (same as the player) |
| Third person (orbit camera) | the **camera**, not the character: the compass should match what you see. With Cinemachine, use the Main Camera transform (the Brain drives it), see [[Cinemachine 3]] |
| Top-down / isometric | usually no compass; if you have one, the player's facing |
Bearings to markers are measured from the **player's** position (that is where the distance means something), while the strip is centred on the **camera's** heading.
## 5.3 `Wayfinding.uss`, compass section
```css
/* ---------- Compass ---------- */
.compass {
position: absolute;
top: 20px;
left: 50%;
width: 640px;
margin-left: -320px; /* centre without depending on percentage translate */
height: 64px;
overflow: hidden; /* rectangle clip, no stencil */
background-color: rgba(10, 14, 20, 0.55);
/* no border-radius: a rounded overflow-hidden element switches from rectangle clipping to stencil masking */
}
.compass__strip,
.compass__markers {
position: absolute;
left: 0; top: 0; right: 0; bottom: 0;
}
.compass__tick {
position: absolute;
left: 0;
top: 0;
width: 2px;
height: 7px;
background-color: rgba(230, 236, 245, 0.55);
}
.compass__tick--major {
height: 13px;
background-color: rgba(230, 236, 245, 0.9);
}
.compass__label {
position: absolute;
left: 0;
top: 13px;
width: 40px;
height: 16px;
-unity-text-align: upper-center;
font-size: 12px;
color: rgb(170, 180, 200);
padding: 0; margin: 0;
}
.compass__label--cardinal {
font-size: 15px;
-unity-font-style: bold;
color: rgb(240, 244, 250);
}
.compass__label--north {
color: rgb(255, 210, 90);
}
.compass__needle {
position: absolute;
left: 319px;
top: 0;
width: 2px;
height: 16px;
background-color: rgb(255, 210, 90);
}
.compass__heading {
position: absolute;
right: 6px;
top: 2px;
font-size: 11px;
color: rgb(140, 154, 175);
padding: 0; margin: 0;
}
.compass-marker {
position: absolute;
left: 0;
top: 30px;
width: 48px;
align-items: center;
}
.compass-marker__icon {
width: 18px;
height: 18px;
}
.compass-marker--tracked .compass-marker__icon {
width: 24px;
height: 24px;
}
.compass-marker--edge {
opacity: 0.55;
}
.compass-marker__distance {
font-size: 11px;
-unity-text-align: upper-center;
color: rgb(230, 236, 245);
padding: 0; margin: 0;
-unity-text-outline-width: 1px;
-unity-text-outline-color: rgba(0, 0, 0, 0.8);
}
.compass-marker__elevation {
position: absolute;
left: 36px;
top: 0;
width: 9px;
height: 9px;
}
```
## 5.4 `CompassView.cs`
```csharp
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Wayfinding
{
/// <summary>
/// Horizontal compass: generated ticks and labels, heading readout, and markers placed by bearing
/// from the player, centred on the camera heading. NOT compiled.
/// </summary>
[DefaultExecutionOrder(50)]
public sealed class CompassView : PanelViewBase
{
public enum Mapping { Linear, MatchCamera }
[Header("Sources")]
[Tooltip("Usually the main camera.")]
[SerializeField] Transform headingSource;
[Tooltip("Distances and bearings are measured from here.")]
[SerializeField] Transform player;
[Tooltip("Needed for Mapping = MatchCamera.")]
[SerializeField] Camera viewCamera;
[Header("Strip")]
[SerializeField, Range(60f, 360f)] float fieldOfView = 180f;
[SerializeField] Mapping mapping = Mapping.Linear;
[SerializeField, Range(1, 15)] int tickStep = 5;
[SerializeField, Range(5, 90)] int labelStep = 15;
[Header("Markers")]
[Tooltip("Show the up/down hint when the height difference exceeds this.")]
[SerializeField, Min(0.5f)] float elevationThreshold = 3f;
struct StripItem
{
public VisualElement element;
public float angle;
public float halfWidth;
}
sealed class Entry
{
public VisualElement root, icon;
public Label distance;
public ArrowGlyph elevation;
public int lastMeters = -1;
public int lastElevation; // -1, 0, +1
public bool edge;
}
static readonly string[] s_HeadingText = BuildHeadingText();
VisualElement _compass, _strip, _markers;
Label _headingLabel;
readonly List<StripItem> _items = new List<StripItem>(128);
readonly Dictionary<MapMarker, Entry> _entries = new Dictionary<MapMarker, Entry>(32);
float _width = float.NaN;
float _lastHeading = float.NaN;
int _lastHeadingInt = -1;
static string[] BuildHeadingText()
{
var a = new string[360];
for (int i = 0; i < 360; i++) a[i] = i.ToString("000"); // allocated once, reused forever
return a;
}
static string LabelFor(int angle) => angle switch
{
0 => "N", 45 => "NE", 90 => "E", 135 => "SE",
180 => "S", 225 => "SW", 270 => "W", 315 => "NW",
_ => angle.ToString()
};
// ---------- binding ----------
protected override void Bind(VisualElement root)
{
_compass = root.Q<VisualElement>("compass");
_strip = root.Q<VisualElement>("compass-strip");
_markers = root.Q<VisualElement>("compass-markers");
_headingLabel = root.Q<Label>("compass-heading");
_compass.RegisterCallback<GeometryChangedEvent>(OnGeometry);
BuildStrip();
_lastHeading = float.NaN;
_lastHeadingInt = -1;
MarkerRegistry.Added += OnMarkerAdded;
MarkerRegistry.Removed += OnMarkerRemoved;
MarkerRegistry.Changed += OnMarkerChanged;
MarkerRegistry.TrackedChanged += OnTrackedChanged;
foreach (MapMarker m in MarkerRegistry.All) OnMarkerAdded(m);
}
protected override void Unbind()
{
MarkerRegistry.Added -= OnMarkerAdded;
MarkerRegistry.Removed -= OnMarkerRemoved;
MarkerRegistry.Changed -= OnMarkerChanged;
MarkerRegistry.TrackedChanged -= OnTrackedChanged;
_compass?.UnregisterCallback<GeometryChangedEvent>(OnGeometry);
foreach (StripItem item in _items) item.element.RemoveFromHierarchy();
_items.Clear();
foreach (Entry e in _entries.Values) e.root.RemoveFromHierarchy();
_entries.Clear();
}
void OnGeometry(GeometryChangedEvent evt)
{
_width = evt.newRect.width;
_lastHeading = float.NaN; // force a strip refresh at the new width
}
void BuildStrip()
{
for (int a = 0; a < 360; a += tickStep)
{
bool major = a % labelStep == 0;
var tick = new VisualElement { pickingMode = PickingMode.Ignore, usageHints = UsageHints.DynamicTransform };
tick.AddToClassList("compass__tick");
if (major) tick.AddToClassList("compass__tick--major");
_strip.Add(tick);
_items.Add(new StripItem { element = tick, angle = a, halfWidth = 1f }); // USS width 2px
if (!major) continue;
var label = new Label(LabelFor(a)) { pickingMode = PickingMode.Ignore, usageHints = UsageHints.DynamicTransform };
label.AddToClassList("compass__label");
if (a % 45 == 0) label.AddToClassList("compass__label--cardinal");
if (a == 0) label.AddToClassList("compass__label--north");
_strip.Add(label);
_items.Add(new StripItem { element = label, angle = a, halfWidth = 20f }); // USS width 40px
}
}
// ---------- registry ----------
void OnMarkerAdded(MapMarker marker)
{
if (!IsBound || _entries.ContainsKey(marker)) return;
var e = new Entry
{
root = new VisualElement { pickingMode = PickingMode.Ignore, usageHints = UsageHints.DynamicTransform },
icon = new VisualElement { pickingMode = PickingMode.Ignore },
distance = new Label { pickingMode = PickingMode.Ignore },
elevation = new ArrowGlyph()
};
e.root.AddToClassList("compass-marker");
e.icon.AddToClassList("compass-marker__icon");
e.distance.AddToClassList("compass-marker__distance");
e.elevation.AddToClassList("compass-marker__elevation");
e.elevation.visible = false;
e.root.Add(e.icon);
e.root.Add(e.distance);
e.root.Add(e.elevation);
_markers.Add(e.root);
_entries.Add(marker, e);
ApplyKind(marker, e);
}
void OnMarkerRemoved(MapMarker marker)
{
if (!_entries.TryGetValue(marker, out Entry e)) return;
e.root.RemoveFromHierarchy();
_entries.Remove(marker);
}
void OnMarkerChanged(MapMarker marker)
{
if (_entries.TryGetValue(marker, out Entry e)) ApplyKind(marker, e);
}
void OnTrackedChanged(MapMarker tracked)
{
foreach (KeyValuePair<MapMarker, Entry> pair in _entries)
{
bool isTracked = pair.Key == tracked;
pair.Value.root.EnableInClassList("compass-marker--tracked", isTracked);
if (isTracked) pair.Value.root.BringToFront(); // draw above other markers
}
}
void ApplyKind(MapMarker marker, Entry e)
{
bool show = marker.ShowsOn(MarkerChannels.Compass);
e.root.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
if (!show) return;
MarkerKind k = marker.Kind;
e.icon.style.backgroundImage = k.icon != null ? new StyleBackground(k.icon) : new StyleBackground(StyleKeyword.None);
e.icon.style.unityBackgroundImageTintColor = k.tint;
e.distance.style.display = k.showDistance ? DisplayStyle.Flex : DisplayStyle.None;
e.elevation.arrowColor = k.tint;
e.root.EnableInClassList("compass-marker--tracked", marker == MarkerRegistry.Tracked);
e.lastMeters = -1;
}
// ---------- per frame ----------
void LateUpdate()
{
if (!IsBound || headingSource == null || player == null) return;
if (float.IsNaN(_width) || _width <= 0f) return;
float heading = MapMath.Heading(headingSource.forward);
// Strip: only when the heading actually changed (dirty flag).
if (float.IsNaN(_lastHeading) || Mathf.Abs(Mathf.DeltaAngle(_lastHeading, heading)) > 0.01f)
{
_lastHeading = heading;
UpdateStrip(heading);
}
int headingInt = Mathf.RoundToInt(heading) % 360;
if (headingInt != _lastHeadingInt)
{
_lastHeadingInt = headingInt;
_headingLabel.text = s_HeadingText[headingInt]; // no allocation
}
UpdateMarkers(heading);
}
float AngleToX(float deltaDegrees)
{
if (mapping == Mapping.MatchCamera && viewCamera != null)
{
// Perspective-matched: x follows tan() like the camera projection, so a marker sits
// horizontally over its target when that target is on screen. Only valid for |delta| < 90.
float hfov = Camera.VerticalToHorizontalFieldOfView(viewCamera.fieldOfView, viewCamera.aspect) * 0.5f;
float d = Mathf.Clamp(deltaDegrees, -89f, 89f);
float t = Mathf.Tan(d * Mathf.Deg2Rad) / Mathf.Tan(hfov * Mathf.Deg2Rad);
return _width * 0.5f + t * _width * 0.5f;
}
return _width * 0.5f + deltaDegrees * (_width / fieldOfView);
}
void UpdateStrip(float heading)
{
float half = fieldOfView * 0.5f;
for (int i = 0; i < _items.Count; i++)
{
StripItem item = _items[i];
float d = Mathf.DeltaAngle(heading, item.angle);
bool vis = Mathf.Abs(d) <= half + 8f; // a little margin so labels slide out, not pop
if (item.element.visible != vis) item.element.visible = vis;
if (!vis) continue;
item.element.style.translate = new Translate(AngleToX(d) - item.halfWidth, 0f);
}
}
void UpdateMarkers(float heading)
{
float half = fieldOfView * 0.5f;
Vector3 from = player.position;
foreach (KeyValuePair<MapMarker, Entry> pair in _entries)
{
Entry e = pair.Value;
if (e.root.style.display.value == DisplayStyle.None) continue;
MapMarker marker = pair.Key;
MarkerKind k = marker.Kind;
Vector3 target = marker.GroundPosition;
float dist = MapMath.FlatDistance(from, target);
if (k.maxDistance > 0f && dist > k.maxDistance) { e.root.visible = false; continue; }
float d = MapMath.RelativeBearing(heading, MapMath.Bearing(from, target));
bool edge = Mathf.Abs(d) > half;
if (edge)
{
if (!k.clampToScreenEdge) { e.root.visible = false; continue; }
d = Mathf.Sign(d) * half; // pin to the strip's end
}
e.root.visible = true;
if (edge != e.edge) { e.edge = edge; e.root.EnableInClassList("compass-marker--edge", edge); }
e.root.style.translate = new Translate(AngleToX(d) - 24f, 0f); // half of the 48px USS width
if (k.showDistance)
{
int meters = Mathf.RoundToInt(dist);
if (meters != e.lastMeters) // text regenerates geometry: only on change
{
e.lastMeters = meters;
e.distance.text = MapMath.FormatDistance(meters);
}
}
float dy = target.y - from.y;
int elev = dy > elevationThreshold ? 1 : dy < -elevationThreshold ? -1 : 0;
if (elev != e.lastElevation)
{
e.lastElevation = elev;
e.elevation.visible = elev != 0;
e.elevation.style.rotate = new Rotate(elev < 0 ? 180f : 0f); // glyph points up by default
}
}
}
}
}
```
## 5.5 Walking through the important parts
- **Generated strip, not a scrolling texture.** The classic trick is a 360° texture with UV scrolling. In UI Toolkit, positioning ~100 small elements with `translate` is simpler, crisp at any resolution, localizable (the labels are text) and easy to style per element (north in gold). The elements are created once; per frame only `translate` and `visible` change, and only when the heading changed.
- **Wrap-around for free.** `DeltaAngle(heading, angle)` is the only place angles are compared. A tick at 0° and a heading of 359° gives +1°, so the tick is just right of centre. No `if (angle > 180)` branches anywhere.
- **Heading text without allocations.** 360 strings are built once in a static array. Assigning an existing string to `Label.text` still regenerates the label's text geometry, so the code also skips the assignment when the integer did not change.
- **Distance labels.** Same rule: only when the rounded metres change. At walking speed that is a few updates per second per marker, not 60.
- **Edge clamping.** A tracked objective behind you sits at the strip's end with reduced opacity, which tells the player "turn around". Untracked kinds (for example "nearby loot") just disappear (`clampToScreenEdge` off).
- **Elevation hint.** A small up/down arrow when the objective is more than `elevationThreshold` metres above or below. It saves a lot of "I'm standing right on it, where is it?" moments in multi-storey levels.
- **Linear vs MatchCamera mapping.** With linear mapping a marker 30° to the right is always the same distance from centre. But the camera's perspective projection places on-screen objects by `tan(angle)`, so a linear compass marker does not sit exactly above its on-screen target. `MatchCamera` uses `tan` so that, inside the camera's horizontal FOV, the compass marker lines up with the target. Set `fieldOfView` close to the camera's horizontal FOV when you use it (part 6's screen markers make the alignment easy to check).
## 5.6 Design notes
- **Clean Screen ([[Level Up! (Review)]], Level 8).** Fill the compass with every NPC and chest and it turns into noise. A good default is the tracked objective, the player waypoint and at most one or two other kinds with a `maxDistance`.
- **Quest integration.** When a quest becomes tracked, call `MarkerRegistry.SetTracked` on its objective marker. Part 6 includes a bridge for the quest givers from [[Quest Systems]].
- **Accessibility.** Cardinal letters and numbers are text, so they scale with your UI text settings ([[Accessibility]]) and can be localized ([[Localization]]): put "N/E/S/W" in a string table.
## 5.7 Test
1. Add `CompassView` to `WayfindingHUD`. Heading Source = Main Camera, Player = player, View Camera = Main Camera.
2. Play and turn slowly through north: labels slide through without jumping, and "N" is gold.
3. Track the waypoint from part 4: its icon appears with a distance. Turn your back to it: it pins to the strip's edge at reduced opacity.
4. Switch Mapping to MatchCamera, set Field Of View to about your camera's horizontal FOV, and check that the marker sits above the waypoint's on-screen position (part 6).
## Sources
- `Mathf.DeltaAngle`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Mathf.DeltaAngle.html
- `Camera.VerticalToHorizontalFieldOfView`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Camera.VerticalToHorizontalFieldOfView.html
- USS transform (`translate`, transforms do not recalculate layout): https://docs.unity3d.com/6000.5/Documentation/Manual/UIE-Transform.html
- `UsageHints.DynamicTransform`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.UsageHints.DynamicTransform.html
- `VisualElement.usageHints` (set before adding to a panel): https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.VisualElement-usageHints.html
- `VisualElement.BringToFront`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.VisualElement.BringToFront.html
- `Label`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/UIElements.Label.html
- Masking (rectangle clip vs stencil for rounded corners): https://docs.unity3d.com/6000.5/Documentation/Manual/UIE-masking.html