Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Assets/1.TeamWorkspace/MainMenu/Scene/Module Select.unity
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ MonoBehaviour:
- {fileID: 2800000, guid: 9d4aec44cae8848019e0e5b106b69e7b, type: 3}
- {fileID: 2800000, guid: 072659c261670478192bba1df123a40f, type: 3}
distance: 2
canvasScale: 0.0015
canvasScale: 0.0013
recentreAngle: 40
recentreSpeed: 2.5
inputGrace: 0.6
Expand Down
38 changes: 35 additions & 3 deletions Assets/1.TeamWorkspace/MainMenu/Scripts/ModuleSelectMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class ModuleSelectMenu : MonoBehaviour
[Tooltip("Metres in front of the player.")]
public float distance = 2.0f;
[Tooltip("World metres per canvas unit. The layout below is authored in millimetres.")]
public float canvasScale = 0.0015f;
public float canvasScale = 0.0013f;
[Tooltip("Degrees the player may turn away before the menu drifts back in front of them.")]
public float recentreAngle = 40f;
public float recentreSpeed = 2.5f;
Expand Down Expand Up @@ -92,6 +92,7 @@ class Entry
bool launching, placed;
float fade;
Vector3 targetPos;
float placedEyeY;
string pendingScene;

// ------------------------------------------------------------------ lifecycle
Expand All @@ -109,13 +110,16 @@ void Awake()
BuildCanvas();
BuildFader();
SelectFirstAvailable();
// Hidden until it has been put in front of a tracked head; see Place.
root.gameObject.SetActive(false);
}

void Update()
{
if (!ResolveCamera()) return;
input.Update();
Place();
if (!placed) return;

if (launching)
{
Expand Down Expand Up @@ -232,23 +236,33 @@ void Launch(Entry e)
/// <summary>
/// World-locked, not head-locked: a panel welded to the eyes is unpleasant to read and would
/// make gaze selection impossible. It only drifts back once the player has turned well away.
///
/// On a headset the first frames come before the first tracked head pose: the camera still sits
/// at the rig origin, which on a floor-level rig is the floor. Placing the menu then put it in
/// the ground with only its top edge showing. So it waits for a tracked head, and it snaps
/// again whenever the head height jumps (tracking starting late, a recentre, sitting down).
/// </summary>
void Place()
{
if (!placed && !HeadReady()) return;

Vector3 forward = Flatten(cam.forward);
Vector3 wanted = cam.position + forward * distance;
wanted.y = cam.position.y - 0.12f;

if (!placed)
if (!placed || Mathf.Abs(cam.position.y - placedEyeY) > HeightJump)
{
targetPos = wanted;
root.position = wanted;
root.rotation = Quaternion.LookRotation(Flatten(wanted - cam.position), Vector3.up);
placedEyeY = cam.position.y;
if (!placed) root.gameObject.SetActive(true);
placed = true;
}
else if (Vector3.Angle(forward, Flatten(targetPos - cam.position)) > recentreAngle)
{
targetPos = wanted;
placedEyeY = cam.position.y;
}

float t = 1f - Mathf.Exp(-recentreSpeed * Time.unscaledDeltaTime);
Expand All @@ -261,6 +275,24 @@ void Place()
faderRoot.rotation = cam.rotation;
}

const float HeightJump = 0.3f;

/// <summary>
/// True once the headset reports a tracked head, or straight away when there is no headset
/// (editor, desktop test) and the camera never gets a pose at all.
/// </summary>
bool HeadReady()
{
var head = UnityEngine.XR.InputDevices.GetDeviceAtXRNode(UnityEngine.XR.XRNode.Head);
float age = Time.unscaledTime - born;
if (!head.isValid) return age > 0.25f;
// Never wait forever: if tracking is never reported, show it anyway (the height-jump snap
// still corrects it once a real pose arrives).
if (age > 3f) return true;
return head.TryGetFeatureValue(UnityEngine.XR.CommonUsages.isTracked, out bool tracked) && tracked
&& cam.localPosition.sqrMagnitude > 0.0001f;
}

static Vector3 Flatten(Vector3 v)
{
v.y = 0f;
Expand Down Expand Up @@ -664,7 +696,7 @@ public static class ModuleSelectText
public const string TutorialTitle = "Module 2 - Tutorial";
public const string GamaTitle = "GAMA / IP setup";

public const string Hint = "Look at a module, then press A stick to move | hold B in game to come back here";
public const string Hint = "Look at a module, then press A | in a module, press MENU twice to come back here";
public const string HintDesktop = "Arrows to move, Space to start desktop test mode - no headset detected";
public const string NotInBuild = "Scene missing from the build list (File > Build Profiles)";
}
105 changes: 72 additions & 33 deletions Assets/1.TeamWorkspace/MainMenu/Scripts/ReturnToMenu.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/// <summary>
/// "Hold B to leave" - the way out of a module and back to <see cref="AppFlow.MenuScene"/>.
/// The way out of a module and back to <see cref="AppFlow.MenuScene"/>, in two forms:
/// - press the left controller's MENU button twice (the second within <see cref="ArmSeconds"/>).
/// That is the button a Quest player already reaches for to "go to the menu". Twice, because
/// one stray press must not throw away a child's progress; the first press says what the
/// second will do;
/// - hold B / Y for <see cref="HoldSeconds"/>. B is used because the modules only ever tap it
/// (Module 1's "press anything to fly again", Module 3's "no"); none of them holds it.
/// No module on main reads the menu button.
///
/// It installs itself into every scene through <see cref="RuntimeInitializeOnLoadMethod"/> and
/// survives scene loads, so neither module scene nor any module script has to be touched to gain
/// it. That is deliberate: <c>Module_1_MainScene.unity</c> is ~38k lines of YAML and every edit to
/// it is a merge conflict waiting for whoever is working on the other branch.
///
/// The hold is long enough (<see cref="HoldSeconds"/>) that nobody leaves a module by fumbling a
/// button, and a progress bar appears while holding so it is discoverable rather than a secret.
/// B / Y is used because the modules only ever tap it (Module 1's "press anything to fly again",
/// Module 3's "no"); none of them holds it.
/// it. That is deliberate: the module scenes are tens of thousands of lines of YAML and every edit
/// to one is a merge conflict waiting for whoever is working on the other branch.
/// </summary>
public class ReturnToMenu : MonoBehaviour
{
public const float HoldSeconds = 1.5f;
public const float ArmSeconds = 3f;
const float ShowAfterSeconds = 0.3f;

static ReturnToMenu instance;
Expand All @@ -27,9 +31,10 @@ public class ReturnToMenu : MonoBehaviour
Transform cam;
RectTransform root;
CanvasGroup group;
Image fill;
Image track, fill;
TextMeshProUGUI label;
bool leaving;
float armedUntil;

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void Install()
Expand All @@ -44,13 +49,16 @@ void Awake()
{
BuildIndicator();
SceneManager.sceneLoaded += OnSceneLoaded;
// Installed after the first scene has loaded, so its sceneLoaded has already gone by.
OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single);
}

// This object outlives every scene, so the "already leaving" latch has to be cleared on each
// load; otherwise only the first trip back to the menu per app launch would work.
// This object outlives every scene, so per-scene state is reset on each load; in particular
// the "already leaving" latch, or only the first trip back per app launch would work.
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
leaving = false;
armedUntil = 0f;
}

void Update()
Expand All @@ -69,25 +77,40 @@ void Update()
}

input.Update();
float held = Mathf.Clamp01(input.SecondaryHeld / HoldSeconds);
float now = Time.unscaledTime;

if (input.MenuDown)
{
if (now < armedUntil) { Leave(); return; }
armedUntil = now + ArmSeconds;
input.Rumble();
}
if (input.SecondaryHeld >= HoldSeconds) { Leave(); return; }

// A quick tap of B is an answer in Module 3 ("no"), so the bar only shows once the press is
// clearly a hold, rather than flashing up on every tap.
bool show = input.SecondaryHeld > ShowAfterSeconds;
group.alpha = Mathf.MoveTowards(group.alpha, show ? 1f : 0f, Time.unscaledDeltaTime * 8f);
fill.fillAmount = held;
label.text = ReturnToMenuText.Holding;
string text = null;
bool bar = false;
if (input.SecondaryHeld > ShowAfterSeconds) { text = ReturnToMenuText.Holding; bar = true; }
else if (now < armedUntil) text = ReturnToMenuText.PressAgain;

group.alpha = Mathf.MoveTowards(group.alpha, text != null ? 1f : 0f, Time.unscaledDeltaTime * 6f);
if (text != null) label.text = text;
track.enabled = fill.enabled = bar;
fill.fillAmount = Mathf.Clamp01(input.SecondaryHeld / HoldSeconds);
// Text in the middle on its own; above the bar when there is one.
label.rectTransform.offsetMin = new Vector2(20f, bar ? 44f : 10f);

// Sits below the line of sight so it never covers what the player is doing.
root.position = cam.position + cam.rotation * new Vector3(0f, -0.26f, 0.9f);
root.position = cam.position + cam.rotation * new Vector3(0f, -0.32f, 0.9f);
root.rotation = cam.rotation;
}

if (input.SecondaryHeld >= HoldSeconds)
{
leaving = true;
input.Rumble(0.6f, 0.15f);
AppFlow.ReturnToMenu();
}
void Leave()
{
leaving = true;
input.Rumble(0.6f, 0.15f);
AppFlow.ReturnToMenu();
}

void OnDestroy()
Expand All @@ -101,41 +124,56 @@ void BuildIndicator()
int layer = LayerMask.NameToLayer("UI");
if (layer < 0) layer = 5;

var go = new GameObject("Hold Indicator") { layer = layer };
var go = new GameObject("Return Indicator") { layer = layer };
go.transform.SetParent(transform, false);
var canvas = go.AddComponent<Canvas>();
canvas.renderMode = RenderMode.WorldSpace;
canvas.sortingOrder = 1000;

root = (RectTransform)go.transform;
root.sizeDelta = new Vector2(560f, 120f);
root.sizeDelta = new Vector2(620f, 130f);
root.localScale = Vector3.one * 0.001f;
group = go.AddComponent<CanvasGroup>();
group.alpha = 0f;

var bg = Add<Image>("Panel", root);
bg.color = new Color(0.02f, 0.06f, 0.09f, 0.78f);
bg.color = new Color(0.02f, 0.06f, 0.09f, 0.82f);
Stretch(bg.rectTransform);
OnTop(bg);

label = Add<TextMeshProUGUI>("Label", root);
label.fontSize = 30;
label.color = Color.white;
label.alignment = TextAlignmentOptions.Center;
label.raycastTarget = false;
var lr = label.rectTransform;
lr.anchorMin = new Vector2(0f, 1f); lr.anchorMax = new Vector2(1f, 1f); lr.pivot = new Vector2(0.5f, 1f);
lr.offsetMin = new Vector2(16f, 0f); lr.offsetMax = new Vector2(-16f, -14f);
lr.sizeDelta = new Vector2(lr.sizeDelta.x, 46f);
label.textWrappingMode = TextWrappingModes.Normal;
Stretch(label.rectTransform);
label.rectTransform.offsetMax = new Vector2(-20f, -10f);
// TMP draws with its own material, so it needs its own copy to ignore depth.
label.fontMaterial.SetInt("unity_GUIZTestMode", (int)CompareFunction.Always);

var track = Add<Image>("Track", root);
track = Add<Image>("Track", root);
track.color = new Color(1f, 1f, 1f, 0.18f);
Bar(track.rectTransform);
OnTop(track);

fill = Add<Image>("Fill", root);
fill.color = new Color32(0x3F, 0xCB, 0x4B, 0xFF);
fill.type = Image.Type.Filled;
fill.fillMethod = Image.FillMethod.Horizontal;
fill.fillAmount = 0f;
Bar(fill.rectTransform);
OnTop(fill);
}

/// <summary>
/// The prompt floats 0.9 m ahead, and in Module 1 a wall or a flower is often nearer than that.
/// Drawn without a depth test it stays readable instead of disappearing into the scenery.
/// </summary>
static void OnTop(Graphic g)
{
var m = new Material(Graphic.defaultGraphicMaterial);
m.SetInt("unity_GUIZTestMode", (int)CompareFunction.Always);
g.material = m;
}

static T Add<T>(string name, Transform parent) where T : Component
Expand Down Expand Up @@ -168,5 +206,6 @@ static void Bar(RectTransform rt)

public static class ReturnToMenuText
{
public const string Holding = "Keep holding B to go back to the menu";
public const string PressAgain = "Press MENU again to go back to the module menu";
public const string Holding = "Keep holding B to go back to the module menu";
}
11 changes: 8 additions & 3 deletions Assets/1.TeamWorkspace/MainMenu/Scripts/XRButtons.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class XRButtons
// Held this frame (either hand).
public bool Primary { get; private set; } // A / X
public bool Secondary { get; private set; } // B / Y
public bool Menu { get; private set; } // the left controller's menu button
public bool Trigger { get; private set; }
public bool Grip { get; private set; }
public Vector2 Stick { get; private set; }
Expand All @@ -30,14 +31,15 @@ public class XRButtons
public bool PrimaryDown { get; private set; }
public bool TriggerDown { get; private set; }
public bool SecondaryDown { get; private set; }
public bool MenuDown { get; private set; }

/// <summary>Seconds B/Y has been held, or 0 when it is up.</summary>
public float SecondaryHeld { get; private set; }
/// <summary>Any button or stick input at all - for "press anything to continue".</summary>
public bool AnyInput { get; private set; }
public bool HasControllers => left.isValid || right.isValid;

bool primaryLast, secondaryLast, triggerLast;
bool primaryLast, secondaryLast, triggerLast, menuLast;

/// <summary>Stick flicks, debounced into discrete steps so a held stick does not race through a list.</summary>
public int StepX { get; private set; }
Expand All @@ -56,6 +58,7 @@ public void Update()

Primary = Button(CommonUsages.primaryButton);
Secondary = Button(CommonUsages.secondaryButton);
Menu = Button(CommonUsages.menuButton);
Trigger = Button(CommonUsages.triggerButton);
Grip = Button(CommonUsages.gripButton);
Stick = Axis(CommonUsages.primary2DAxis);
Expand All @@ -66,8 +69,9 @@ public void Update()

PrimaryDown = Primary && !primaryLast;
SecondaryDown = Secondary && !secondaryLast;
MenuDown = Menu && !menuLast;
TriggerDown = Trigger && !triggerLast;
primaryLast = Primary; secondaryLast = Secondary; triggerLast = Trigger;
primaryLast = Primary; secondaryLast = Secondary; triggerLast = Trigger; menuLast = Menu;

// Capped per frame: a hitch (a scene loading, a stutter) must not turn a tap into a long hold.
SecondaryHeld = Secondary ? SecondaryHeld + Mathf.Min(Time.unscaledDeltaTime, MaxHoldStep) : 0f;
Expand Down Expand Up @@ -119,13 +123,14 @@ static InputDevice FirstDevice(InputDeviceCharacteristics characteristics)
}

#if UNITY_EDITOR
// Left/right arrow or A/D to move, Space/Enter to confirm, Escape as B/Y.
// Left/right arrow or A/D to move, Space/Enter to confirm, Escape as B/Y, M as the menu button.
void KeyboardFallback()
{
var kb = UnityEngine.InputSystem.Keyboard.current;
if (kb == null) return;
Primary = kb.spaceKey.isPressed || kb.enterKey.isPressed;
Secondary = kb.escapeKey.isPressed;
Menu = kb.mKey.isPressed;
Trigger = kb.leftCtrlKey.isPressed;
float x = (kb.rightArrowKey.isPressed || kb.dKey.isPressed ? 1f : 0f)
- (kb.leftArrowKey.isPressed || kb.aKey.isPressed ? 1f : 0f);
Expand Down
Loading