using System.Collections;
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace jeanf.universalplayer.tests
{
///
/// Locomotion feel for the M&K / gamepad modes: weight & momentum (velocity ramps
/// instead of snapping), sprint, crouch (capsule shrink + blocked stand-up), and the
/// FpsCameraFeel head bob / camera roll — including the hard rule that none of it
/// runs in XR (artificial camera motion in VR causes motion sickness).
///
public class LocomotionFeelTests
{
private GameObject _floor;
private GameObject _player;
private GameObject _ceiling;
private GameObject _lookRig;
private Transform _cameraOffset;
private CharacterController _controller;
private PlayerMovement _movement;
private bool _prevIgnoreDefaultCollision;
[UnitySetUp]
public IEnumerator SetUp()
{
// The rigs live on the Default layer; projects (like this one) may disable
// Default<->Default in the collision matrix. Pin it on for the test.
_prevIgnoreDefaultCollision = Physics.GetIgnoreLayerCollision(0, 0);
Physics.IgnoreLayerCollision(0, 0, false);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.KeyboardMouse;
_floor = GameObject.CreatePrimitive(PrimitiveType.Cube);
_floor.name = "Floor";
_floor.transform.localScale = new Vector3(20f, 1f, 20f);
_floor.transform.position = new Vector3(0f, -0.5f, 0f);
_player = new GameObject("Player");
_player.SetActive(false);
_player.transform.position = new Vector3(0f, 1.1f, 0f);
_controller = _player.AddComponent();
// Prefab-faithful layout: the shipped Player prefab has PlayerMovement on a
// GRANDCHILD ('Player > Locomotion > Move') of the root that owns the
// CharacterController. The crouch stand-up regression (the player's own
// capsule read as an obstruction) only reproduces with this split — a
// same-object rig silently passes.
var locomotion = new GameObject("Locomotion");
locomotion.transform.SetParent(_player.transform, false);
var move = new GameObject("Move");
move.transform.SetParent(locomotion.transform, false);
_movement = move.AddComponent();
SetField(_movement, "controller", _controller);
// Camera rig for the crouch camera-height tests. The FPSCameraMovement
// component's own lifecycle needs a full camera + input wiring, so its
// GameObject stays INACTIVE forever — PlayerMovement only reads CameraOffset.
_lookRig = new GameObject("LookRig");
_lookRig.SetActive(false);
_cameraOffset = new GameObject("CameraOffset").transform;
_cameraOffset.SetParent(_lookRig.transform, false);
_cameraOffset.localPosition = new Vector3(0f, 1.65f, 0f);
var look = _lookRig.AddComponent();
SetField(look, "cameraOffset", _cameraOffset);
SetField(_movement, "mouseLook", look);
SetField(_movement, "speed", 4f);
// Gentle ramp so even a slow editor frame cannot reach top speed in one step
// (keeps the momentum assertions deterministic).
SetField(_movement, "speedChangeRate", 4f);
_player.SetActive(true);
// Let gravity settle the controller onto the floor.
for (var i = 0; i < 10; i++) yield return null;
}
[UnityTearDown]
public IEnumerator TearDown()
{
Physics.IgnoreLayerCollision(0, 0, _prevIgnoreDefaultCollision);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.KeyboardMouse;
Object.Destroy(_player);
Object.Destroy(_floor);
if (_lookRig != null) Object.Destroy(_lookRig);
_lookRig = null;
// The crouch test's ceiling: destroyed HERE, not only mid-test — when its
// assert throws, the in-test Destroy never runs and the leaked ceiling
// wedges every later player (spawned overlapping it, Move() achieves
// nothing), which broke the head-bob test with a mystifying zero offset.
if (_ceiling != null) Object.Destroy(_ceiling);
_ceiling = null;
yield return null;
}
private static void SetField(object target, string field, object value)
{
var info = target.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic);
Assert.That(info, Is.Not.Null, $"Field '{field}' not found on {target.GetType().Name} — was it renamed? Update LocomotionFeelTests alongside the refactor.");
info.SetValue(target, value);
}
private void StartMoving(Vector2 input)
{
_movement.SetMoveValue(input);
_movement.SetIsMoving(true);
}
private void StopMoving()
{
_movement.SetMoveValue(Vector2.zero);
_movement.SetIsMoving(false);
}
private IEnumerator Frames(int count)
{
for (var i = 0; i < count; i++) yield return null;
}
[UnityTest]
public IEnumerator Momentum_VelocityRampsUp_AndDecaysAfterRelease()
{
StartMoving(Vector2.up);
yield return null;
yield return null;
var earlySpeed = _movement.PlanarVelocity.magnitude;
Assert.That(earlySpeed, Is.GreaterThan(0f), "No movement at all — momentum move is not running.");
Assert.That(earlySpeed, Is.LessThan(3.9f),
"Velocity snapped (almost) straight to top speed — the acceleration ramp (speedChangeRate) is not being applied.");
yield return new WaitForSeconds(1.5f); // wall time, not frames: the ramp is m/s², the editor fps varies
Assert.That(_movement.PlanarVelocity.magnitude, Is.EqualTo(4f).Within(0.2f),
"Walk speed never reached its target.");
StopMoving();
yield return null;
Assert.That(_movement.PlanarVelocity.magnitude, Is.GreaterThan(0.5f),
"Velocity vanished instantly on release — deceleration (weight) is not being applied.");
yield return new WaitForSeconds(1.5f);
Assert.That(_movement.PlanarVelocity.magnitude, Is.LessThan(0.05f),
"Velocity never decayed back to zero after input stopped.");
}
[UnityTest]
public IEnumerator Sprint_TopSpeedIsHigherThanWalk()
{
StartMoving(Vector2.up);
_movement.SetSprintHeld(true);
// Wall time, not frames: reaching >5 m/s at speedChangeRate 4 m/s² needs ≥1.25s
// — 90 frames on a fast editor is well under that.
yield return new WaitForSeconds(2f);
Assert.That(_movement.PlanarVelocity.magnitude, Is.GreaterThan(5f),
"Sprint did not raise the top speed above walking speed.");
Assert.That(_movement.IsSprinting, Is.True);
_movement.SetSprintHeld(false);
}
[UnityTest]
public IEnumerator Crouch_ShrinksCapsule_AndRefusesToStandUnderCeiling()
{
SetField(_movement, "crouchIsToggle", false); // this test drives HOLD crouch semantics
var standingHeight = _controller.height;
_movement.SetCrouchHeld(true);
yield return new WaitForSeconds(0.5f); // wall time: the crouch blend runs on seconds, not frames
Assert.That(_controller.height, Is.LessThan(standingHeight * 0.7f),
"Crouching did not shrink the CharacterController capsule.");
Assert.That(_movement.IsCrouched, Is.True);
// Ceiling above the crouched player: standing must be refused until it is gone.
// Tracked in a fixture field so TearDown cleans it up even when an assert
// below throws — a leaked ceiling wedges every later test's player.
_ceiling = GameObject.CreatePrimitive(PrimitiveType.Cube);
_ceiling.transform.localScale = new Vector3(4f, 0.5f, 4f);
_ceiling.transform.position = new Vector3(0f, 1.75f, 0f);
// Auto-sync-transforms is off in this project: the new collider is invisible
// to the CanStandUp headroom query until a physics step has run.
yield return new WaitForFixedUpdate();
yield return null;
_movement.SetCrouchHeld(false);
yield return new WaitForSeconds(0.5f);
Assert.That(_movement.IsCrouched, Is.True,
"Player stood up INTO a ceiling — the headroom check (CanStandUp) is broken. " +
$"(root: {_player.transform.position}, height: {_controller.height:F2}, " +
$"blend: {_movement.CrouchBlend:F2}, " +
$"ceilingSeenByQuery: {Physics.Raycast(_player.transform.position, Vector3.up, 5f)})");
Object.Destroy(_ceiling);
yield return Frames(2);
yield return new WaitForSeconds(0.75f);
Assert.That(_controller.height, Is.EqualTo(standingHeight).Within(0.05f),
"Player never stood back up after the ceiling was removed.");
}
[UnityTest]
public IEnumerator Crouch_IgnoresObstructions_OnLayersTheCapsuleCannotCollideWith()
{
SetField(_movement, "crouchIsToggle", false);
var standingHeight = _controller.height;
// A volume collider (scene-streaming zone, audio/quest volume...) on a layer
// the capsule does NOT physically collide with, engulfing the player. Walking
// passes straight through it, so it must never read as a ceiling either —
// it used to lock the crouch anywhere inside such a volume.
var prevIgnore = Physics.GetIgnoreLayerCollision(0, 1);
Physics.IgnoreLayerCollision(0, 1, true);
_ceiling = GameObject.CreatePrimitive(PrimitiveType.Cube);
_ceiling.layer = 1;
_ceiling.transform.localScale = new Vector3(4f, 4f, 4f);
_ceiling.transform.position = new Vector3(0f, 2f, 0f);
yield return new WaitForFixedUpdate();
yield return null;
_movement.SetCrouchHeld(true);
yield return new WaitForSeconds(0.5f);
Assert.That(_movement.IsCrouched, Is.True, "Crouching failed inside the non-colliding volume.");
_movement.SetCrouchHeld(false);
yield return new WaitForSeconds(0.75f);
Physics.IgnoreLayerCollision(0, 1, prevIgnore);
Assert.That(_movement.IsCrouched, Is.False,
"A collider on a layer the capsule cannot collide with blocked the stand-up — " +
"the headroom check must respect the Physics Layer Collision Matrix.");
Assert.That(_controller.height, Is.EqualTo(standingHeight).Within(0.05f));
}
[UnityTest]
public IEnumerator Crouch_IgnoresEngulfingVolume_OnACollidingLayer()
{
SetField(_movement, "crouchIsToggle", false);
var standingHeight = _controller.height;
// The uvs lobby case: a non-trigger proxy volume on a COLLIDING layer (an
// acoustic-geometry box on Default) engulfing the whole player. The capsule
// starts inside it so sweeps ignore it and the player lives in it permanently
// — it must not read as a ceiling when standing up.
_ceiling = GameObject.CreatePrimitive(PrimitiveType.Cube);
_ceiling.name = "EngulfingAudioVolume";
_ceiling.transform.localScale = new Vector3(8f, 6f, 8f);
_ceiling.transform.position = new Vector3(0f, 1.5f, 0f);
yield return new WaitForFixedUpdate();
yield return null;
_movement.SetCrouchHeld(true);
yield return new WaitForSeconds(0.5f);
Assert.That(_movement.IsCrouched, Is.True, "Crouching failed inside the engulfing volume.");
_movement.SetCrouchHeld(false);
yield return new WaitForSeconds(0.75f);
Assert.That(_movement.IsCrouched, Is.False,
"An engulfing volume the crouched body is already inside blocked the stand-up — " +
"standing does not newly enter it, so it must be ignored (Env_*_AudioCollider crouch-lock).");
Assert.That(_controller.height, Is.EqualTo(standingHeight).Within(0.05f));
}
[UnityTest]
public IEnumerator CrouchToggle_SecondPress_StandsBackUp()
{
// Default (shipped) semantics: press toggles down, press again toggles up.
SetField(_movement, "crouchIsToggle", true);
var standingHeight = _controller.height;
_movement.SetCrouchHeld(true); // press
_movement.SetCrouchHeld(false); // release
yield return new WaitForSeconds(0.5f);
Assert.That(_movement.IsCrouched, Is.True, "First crouch press did not crouch the player.");
_movement.SetCrouchHeld(true);
_movement.SetCrouchHeld(false);
yield return new WaitForSeconds(0.75f);
Assert.That(_movement.IsCrouched, Is.False,
"Second crouch press did not stand the player back up. With PlayerMovement on a child of the " +
"capsule root (the prefab layout) the stand-up self-filter used to read the player's own capsule " +
"as a ceiling and lock the crouch forever — in every control scheme.");
Assert.That(_controller.height, Is.EqualTo(standingHeight).Within(0.05f),
"Capsule height never returned to standing.");
}
[UnityTest]
public IEnumerator Jump_WhileCrouchToggled_StandsUp_WithoutJumping()
{
SetField(_movement, "crouchIsToggle", true);
_movement.SetCrouchHeld(true);
_movement.SetCrouchHeld(false);
yield return new WaitForSeconds(0.5f);
Assert.That(_movement.IsCrouched, Is.True);
var jumped = false;
System.Action onJump = () => jumped = true;
PlayerEvents.PlayerJumped += onJump;
try
{
_movement.RequestJump();
yield return new WaitForSeconds(0.75f);
Assert.That(_movement.IsCrouched, Is.False,
"A jump press while crouch-toggled must stand the player up (it used to be silently swallowed).");
Assert.That(jumped, Is.False,
"The stand-up press must not ALSO launch a jump once standing.");
}
finally
{
PlayerEvents.PlayerJumped -= onJump;
}
}
[UnityTest]
public IEnumerator Crouch_CameraHeight_ReappliesAfterSchemeSwitchReset()
{
SetField(_movement, "crouchIsToggle", true);
var standingCameraY = _cameraOffset.localPosition.y;
_movement.SetCrouchHeld(true);
_movement.SetCrouchHeld(false);
yield return new WaitForSeconds(0.5f);
var crouchedCameraY = _cameraOffset.localPosition.y;
Assert.That(crouchedCameraY, Is.LessThan(standingCameraY - 0.2f),
"Crouching did not lower the camera offset.");
// A control-scheme switch resets the camera rig to the authored standing eye
// height (FPSCameraMovement.ResetCameraOffset). The crouch is still active, so
// the crouched height must win back within a frame — otherwise the player is
// left with a standing camera but crouched speed/head-bob (the gamepad->mkb
// desync bug).
_cameraOffset.localPosition = new Vector3(0f, standingCameraY, 0f);
yield return Frames(3);
Assert.That(_cameraOffset.localPosition.y, Is.EqualTo(crouchedCameraY).Within(0.05f),
"Camera height was not re-applied after an external rig reset — standing camera with crouched movement.");
}
[UnityTest]
public IEnumerator XrScheme_LocomotionFeelDoesNotMoveThePlayer()
{
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
var before = _player.transform.position;
StartMoving(Vector2.up);
_movement.SetSprintHeld(true);
yield return Frames(30);
var moved = _player.transform.position - before;
moved.y = 0f;
Assert.That(moved.magnitude, Is.LessThan(0.01f),
"PlayerMovement moved the player horizontally while in XR — locomotion feel must be inert there (XRI owns XR locomotion).");
}
[UnityTest]
public IEnumerator HeadBob_OscillatesWhileMoving_AndSettlesWhenStopped()
{
var feel = BuildCameraFeel();
yield return null;
var maxIdle = 0f;
for (var i = 0; i < 20; i++)
{
yield return null;
maxIdle = Mathf.Max(maxIdle, Mathf.Abs(feel.CurrentOffset.y));
}
Assert.That(maxIdle, Is.LessThan(0.001f), "Head bob while standing still.");
StartMoving(Vector2.up);
var maxMoving = 0f;
for (var i = 0; i < 90; i++)
{
yield return null;
maxMoving = Mathf.Max(maxMoving, Mathf.Abs(feel.CurrentOffset.y));
}
Assert.That(maxMoving, Is.GreaterThan(0.005f), "No head bob while walking. " +
$"(grounded: {_movement.IsGrounded}, commandedVel: {_movement.PlanarVelocity.magnitude:F2}, " +
$"actualVel: {_movement.ActualPlanarVelocity.magnitude:F2}, root: {_player.transform.position})");
StopMoving();
// Wall time: momentum bleeds at 4 m/s² from ~4 m/s, so the bob stays live for
// up to a second after release — 60 frames on a fast editor is far less.
yield return new WaitForSeconds(1.5f);
Assert.That(feel.CurrentOffset.magnitude, Is.LessThan(0.002f),
"Head bob offset never settled back after movement stopped.");
}
[UnityTest]
public IEnumerator CameraRoll_FollowsStrafe_AndReturnsToZero()
{
var feel = BuildCameraFeel();
yield return null;
StartMoving(Vector2.right);
yield return Frames(45);
Assert.That(feel.CurrentRoll, Is.LessThan(-0.4f),
"Strafing right did not roll the camera (expected a negative z tilt, leaning into the movement).");
StopMoving();
yield return Frames(90);
Assert.That(Mathf.Abs(feel.CurrentRoll), Is.LessThan(0.05f),
"Camera roll never returned to level after the strafe ended.");
}
[UnityTest]
public IEnumerator XrScheme_CameraFeelStaysInert()
{
var feel = BuildCameraFeel();
yield return null;
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
StartMoving(Vector2.right);
_movement.SetSprintHeld(true);
yield return Frames(45);
Assert.That(feel.CurrentOffset.magnitude, Is.LessThan(0.001f),
"FpsCameraFeel applied a position offset in XR — artificial camera motion in VR causes motion sickness.");
Assert.That(Mathf.Abs(feel.CurrentRoll), Is.LessThan(0.05f),
"FpsCameraFeel applied camera roll in XR.");
}
[UnityTest]
public IEnumerator LookSmoothing_EasesTowardTarget_AndSnapsWhenDisabled()
{
// Unit-level: the component is never activated (no Awake), we only exercise
// the private smoothing step against a bare transform.
var rig = new GameObject("LookSmoothingRig");
rig.SetActive(false);
var offset = new GameObject("CameraOffset").transform;
offset.SetParent(rig.transform);
var look = rig.AddComponent();
SetField(look, "cameraOffset", offset);
SetField(look, "_rotation", new Vector2(0f, 40f));
var apply = typeof(FPSCameraMovement).GetMethod("ApplySmoothedRotation", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.That(apply, Is.Not.Null, "FPSCameraMovement.ApplySmoothedRotation was renamed — update LocomotionFeelTests.");
SetField(look, "lookSmoothingSeconds", 0.1f);
apply.Invoke(look, new object[] { 0.016f });
var afterOneStep = offset.localEulerAngles.y;
Assert.That(afterOneStep, Is.GreaterThan(0.5f).And.LessThan(30f),
"With smoothing on, one step should move the camera partway toward the target — not leave it still, not snap it.");
for (var i = 0; i < 300; i++) apply.Invoke(look, new object[] { 0.016f });
Assert.That(Mathf.DeltaAngle(offset.localEulerAngles.y, 40f), Is.EqualTo(0f).Within(0.5f),
"Smoothed look rotation never converged on the target.");
SetField(look, "lookSmoothingSeconds", 0f);
SetField(look, "_rotation", new Vector2(0f, 80f));
apply.Invoke(look, new object[] { 0.016f });
Assert.That(Mathf.DeltaAngle(offset.localEulerAngles.y, 80f), Is.EqualTo(0f).Within(0.01f),
"With smoothing at 0 the rotation must snap straight to the target (raw input).");
Object.DestroyImmediate(rig);
yield return null;
}
private FpsCameraFeel BuildCameraFeel()
{
var cameraOffset = new GameObject("CameraOffset").transform;
cameraOffset.SetParent(_player.transform);
cameraOffset.localPosition = new Vector3(0f, 1.65f, 0f);
var feelNode = new GameObject("CameraFeel");
feelNode.SetActive(false);
feelNode.transform.SetParent(cameraOffset);
feelNode.transform.localPosition = Vector3.zero;
var feel = feelNode.AddComponent();
SetField(feel, "playerMovement", _movement);
SetField(feel, "lookTransform", cameraOffset);
feelNode.SetActive(true);
return feel;
}
}
}