SmoothLocomotion
A class in Root.Township, the global namespace.
Thumbstick movement for a VR player: moves a character controller with gravity, slopes and fall damage, tracks a last safe position and puts the player back there after a bad fall. Runs on the local player's client; the result goes through LocomotionController.
- Listed in Global namespace: S
- Inherits or implements
MonoBehaviour - Attributes
HasMethodApply - Documented in Locomotion
Constructors
| Member | What it is |
|---|---|
SmoothLocomotion() | Unity makes components itself; use AddComponent or spawn a prefab instead of new. |
Fields
| Member | What it is |
|---|---|
Vector3 velocity | Current physics velocity (gravity and momentum) applied on top of input. |
37 private and internal fields
| Member | What it is |
|---|---|
private Transform cachedTransform | The controller's own transform, unparented from the character at start. |
private SmoothLocomotionPlayerController character | The player controller this locomotion moves. |
private CharacterController characterController | Unity CharacterController used for collision and movement. |
private Transform characterTransform | Transform of the player character, used to measure movement each frame. |
private float clampedSpeedSquared | Square of the settings' maximum speed, used to clamp stick movement. |
private Vector2 currentBuildupSpeed | Current smoothed horizontal speed that accelerates and decelerates toward the stick input. |
private CollisionFlags currentCollisionFlags | Collision flags from the last move; IsGrounded reads the Below flag. |
private float fallFromHeight | Highest point since last grounded, used to work out fall damage. |
private float fallingControl | How much stick control is left while falling, from the settings curve over fall time. |
private Vector3 firstForward | Forward direction locked when movement starts, for the locked head and locked controller direction modes. |
private Stat fullnessStat | The player's Fullness stat, used to decide if they can run. |
private Stat hungerStat | The player's Hunger stat, used to decide if they can run. |
private bool isEnabled | Backing field for IsEnabled. |
private bool isLoaded | False until the current chunk has fully loaded; movement and falling wait for it. |
private Func<bool> IsOverridingMovement | Combined delegate from modifiers; true stops the grounded velocity reset. |
private bool isRecovering | True during the fade after a safety recovery; stick input is ignored. |
private float lastHungrySound | Time the too-hungry-to-run sound last played, for its cooldown. |
private Vector3 lastLocalPosition | Unused in this build. |
private Vector3 lastPosition | Unused in this build. |
private bool lockRun | True while toggle-run mode has run locked on. |
private static Logger logger | NLog logger for this class. |
private float minHeightForDamage | Shortest drop that can deal fall damage, from the first key of the fall-damage curve. |
private Func<bool> MovementOverride | Combined delegate from modifiers; true makes this frame skip normal stick movement and gravity. |
private float nextSafetyCheck | Time of the next allowed LastSafePosition update. |
private int personalSpaceLayer | Layer mask for PlayerPersonalSpace; movement into it is blocked. |
private IPlayerControllerMultiLockModel playerControllerMultiLockModel | Injected player controller lock model. |
private Coroutine recoverCoroutine | The running RecoverFromSafetyReposition coroutine, if any. |
private int runningLevel | 1 for walking, 2 for running, 0 with no input. |
private SmoothLocomotionSettings settings | The global SmoothLocomotionSettings (speeds, curves, masks, fall damage). |
private float slipValue | Current slope slip, building from 0 to 1 while on a too-steep surface. |
private MethodSyncStruct<float> syncFallDistance | Method sync that sends fall distance to the server. |
private float timeFalling | Seconds spent falling, used for falling control and disabling teleport mid-fall. |
private static UpdateModule unownedHeightCheck | Update module for unowned height checks; not used by this class in this build. |
private IUnityUpdateMethod updateInput | Registration of UpdateInput on the update module; null until linked to the local player. |
private static UpdateModule updateModule | Shared update module that runs every instance's UpdateInput. |
private bool wasApplyingInput | Whether stick input was applied last frame. |
private bool wasReleased | Whether the run button has been released since last pressed, for toggle run. |
Properties
| Member | What it is |
|---|---|
HandHandler ActiveHand { get; private set; } | Hand used for smooth movement, from the player's settings. |
Vector3 BodyCenter { get; } | Centre of the character controller in world space. |
SmoothLocomotionPlayerController Character { get; } | The player controller this belongs to. |
CharacterController CharacterController { get; } | The Unity character controller used for collision. |
Vector3 CurrentMovingVelocity { get; private set; } | Velocity from stick input this frame. |
IEnumerable<HandHandler> Hands { get; } | The right then left hand handlers. |
bool IsDebugMovement { get; private set; } | True in debug movement mode (no gravity). |
bool IsEnabled { get; set; } | Whether smooth movement is on. Setting it calls SetEnableController. |
bool IsGrounded { get; } | True if the last move touched something below. |
bool IsSafe { get; set; } | Whether the current spot may be saved as a safe position. |
Vector3 LastSafePosition { get; set; } | Last spot judged safe to stand on. Checked every 5 seconds and sent to the server. |
HandHandler LeftHand { get; private set; } | Left hand handler. |
HandHandler OtherHand { get; private set; } | The hand not used for smooth movement. |
Vector3 Position { get; } | Position of the locomotion object. |
HandHandler RightHand { get; private set; } | Right hand handler. |
Events
5 private and internal events
| Member | What it is |
|---|---|
private event GeneralDelegates.ValueUpdater GetFrictionMultiplier | Event the modifiers add to, to change friction applied to velocity. |
private event GeneralDelegates.ValueUpdater GetHeight | Event the modifiers add to, to change the character controller height. |
private event GeneralDelegates.BoolUpdater GetTeleportationBlock | Event from movement-overriding modifiers that can block teleporting. |
private event GeneralDelegates.ValueUpdater GetUpwardGrip | Event the modifiers add to; a value of 1 cancels gravity (used for climbing and similar). |
private event Action OnFixedUpdate | Event of modifier LocomotionUpdate calls, run every physics step. |
Methods
| Member | What it is |
|---|---|
void ApplyMovement(Vector3 velocityXYZ, bool isApplyingGravity) | Moves the character controller, with gravity and friction when allowed. Debug mode moves without either. |
void ForceSetIsLoaded() | Marks the chunk as loaded so movement can start. |
float GetDefaultHeight(out float headHeight) | Controller height from the head height and settings; also returns the head height. |
void InitializeModifier(ISmoothLocomotionModifier modifier) | Adds a modifier (such as climbing) that changes friction, height, upward grip or overrides movement. |
void MoveToSafety() | Moves the player back to the last safe position (nudged away from edges), or to the respawn point if that is no longer safe. |
void RemoveModifier(ISmoothLocomotionModifier modifier) | Removes a modifier's hooks. For a modifier that overrides movement it destroys this object instead. |
void RepositionCharacter() | Moves the player rig so its feet match the character controller, optionally with a head offset or a horizontal limit. |
void RepositionCharacter(Vector3 headOffset) | Moves the player rig so its feet match the character controller, optionally with a head offset or a horizontal limit. |
void RepositionCharacter(float xzLimit) | Moves the player rig so its feet match the character controller, optionally with a head offset or a horizontal limit. |
void SetEnableController(bool isEnabled) | Turns smooth movement on or off (never in flat modes). Swaps the active hand between teleport or turning and smooth movement. |
void ToggleDebug() | Toggles debug movement. |
void TreatAsGrounded() | Resets the fall start height to now, so no fall damage is counted from earlier. |
void WaitForChunkFinishLoad(Chunk chunk) | Holds movement until the given chunk is fully loaded. |
protected void Inject(IPlayerControllerMultiLockModel playerControllerMultiLockModel) | Dependency injection hook for the player controller lock model. |
32 private and internal methods
| Member | What it is |
|---|---|
private void ApplyGravityAndMovement(Vector3 velocityXYZ) | Adds the stored velocity to a move, applies modifier friction and gravity (reduced by upward grip), and moves the controller. |
private void AssignSmoothLocoHand() | Sets ActiveHand and OtherHand from the player's smooth locomotion hand setting. |
private void Awake() | Hooks entity destruction, local player linking and the locomotion controller's PositionChanged event. |
private bool CanTeleportWithSameHand() | True on Meta Quest, or when the active controller has no swipe input, so the stick hand can also teleport. |
private void CheckForInfiniteFall(Vector3 position, float height) | Raycasts down from the player; if no standable ground is found within the settings distance, calls MoveToSafety. |
private Vector3 CheckInput(ref int runningLevel, ref Vector3 firstForward, ref bool isApplyingInput) | Reads the active hand's stick, works out walk or run (with toggle, hunger and speed modifiers) and returns this frame's horizontal move. |
private bool CheckPosition(Vector3 position, RaycastHit hit) | Raycasts 0.3m down against the safety mask. Used by IsSafePosition. |
private void CheckSetEnabled() | Runs once when linked to the local player: creates the fall-damage sync, hand handlers, hunger stats and the input update. |
private void DeadDisable(DamageData hit) | Turns smooth locomotion off when the player is killed. |
private void DealFallDamage(float dropHeight) | Applies fall damage and cripple damage from the settings curves for a given drop height. |
private void Destroy(NetworkEntity characterEntity, bool isUnload) | Destroys this object when the character's entity is destroyed by the scene. |
private IEnumerator FadeBackAfterRecover() (iterator) | Coroutine that waits, then fades the screen back in after a safety recovery. |
private void FinishLoading(Chunk chunk) | Chunk FullyLoaded handler that sets isLoaded so movement can start. |
private void FixedUpdate() | Invokes the registered modifiers' LocomotionUpdate once input updates are running. |
private bool GeneralSetup() | Editor setup: caches the global settings, squared clamp speed, minimum fall-damage height and character transform. |
private void HandleTeleport(PlayerController player, Vector3 oldPosition, Vector3 newPosition, LocomotionFunction function) | On any non-smooth reposition, snaps the controller to the player's feet and resets fall height; on Recovery it starts the fade-out recovery. |
private void IncreaseSlip(Vector3 normal, ref Vector3 gravityAndSlide) | Builds up slip on a steep slope and returns a sideways slide vector along the slope normal. |
private bool IsCloseToGround(Vector3 position, out Vector3 gravityAndSlide) | Checks for standable ground just below, handles slope sliding and records LastSafePosition every 5 seconds on safe ground. |
private bool IsHitNormalSafe(Vector3 normal) | True when a surface normal is flat enough to stand on (y above 0.2). |
private bool IsSafePosition(Vector3 position) | Checks four points around a spot all have safety-mask ground under them. |
private void Move(Vector3 movement) | Moves the character controller and trims velocity to match what the controller actually managed after collisions. |
private void OnDestroy() | Removes the input update and the settings-changed handler. |
private void OnDrawGizmosSelected() | Editor gizmos for the last safe position, the ground check sphere and modifiers. |
private void OnValidate() | Refreshes the settings and minimum fall-damage height in play mode. |
private IEnumerator RecoverFromSafetyReposition() (iterator) | Coroutine that blacks out the screen and blocks input for the recovery duration after MoveToSafety. |
private bool SetupLayer() | Editor setup that caches the PlayerPersonalSpace layer mask. |
private bool ShouldApplyGravityAndMovement(bool isApplyingGravity) | True when gravity is wanted and the character is alive and not downed. |
private bool ShouldIgnoreInput() | True when the player is dead, downed, blocked from locomoting, interrupted by an interaction, or the headset isn't tracking. |
private void SyncFallDistance(IPlayer player, Stream stream, float distance) | Fall-distance message: the client sends the drop height and the server applies fall damage if it came from this player. |
private void TryApplyFallDamage(Vector3 position) | On landing, works out the drop and deals damage (server) or sends it to the server (client), plus landing effects. |
private void UpdateInput() | Main per-frame movement for the local player: height, stick input, teleport enabling, gravity, falling and fall damage. |
private void UpdateSettings(Settings obj) | Re-applies the smooth locomotion on/off setting when game settings change. |
Used in
Members of other types that take, return or hold a SmoothLocomotion: