Import assets from store

This commit is contained in:
Sahik committed 2026-09-23 09:30:04 +08:00
1 parent a05f2e47a2
commit 376e52e323
875 files changed
+128037

No files matched your search

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 435bb249987a4e56b7ced2c9119f0737
timeCreated: 1701895598
@@ -0,0 +1,107 @@
using UnityEngine;
namespace CharacterMovement
{
public class CrouchingState : PlayerStateBase, IGroundLocomotionState
{
public CrouchingState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Crouching");
_playerController.TryCrouch();
_playerController.FallingEvent += OnFalling;
_playerController.InputSource.DashPerformed += OnDash;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (_playerController.HasBufferedJumpIntent && _playerController.TryStand() && _playerController.TryConsumeBufferedJump())
return;
if (_playerController.ShouldEnterAirborneState)
{
_playerController.SwitchState(new FallingState(_playerController));
return;
}
Vector3 movement = _playerController.CalculateMovement();
MoveOnGround(movement, deltaTime);
if (!_playerController.InputSource.IsCrouching && _playerController.TryStand())
{
_playerController.SwitchToBaseGroundLocomotion();
return;
}
if (_playerController.CanMove && _playerController.InputSource.IsMoving)
FaceMovementDirection(movement, deltaTime);
}
public override void Exit()
{
_playerController.FallingEvent -= OnFalling;
_playerController.InputSource.DashPerformed -= OnDash;
}
private void MoveOnGround(Vector3 movement, float deltaTime)
{
RaycastHit? slopeHit = _playerController.OnSlope();
float additionalSpeed = _playerController.CrouchSpeed - _playerController.Speed;
if (slopeHit.HasValue)
{
float slopeAngle = Vector3.Angle(slopeHit.Value.normal, Vector3.up);
if (slopeAngle > _playerController.MaxSlopeAngle)
{
_playerController.SwitchState(new SlidingState(_playerController, slopeHit));
return;
}
Vector3 slopeMovement = Vector3.ProjectOnPlane(movement, slopeHit.Value.normal).normalized;
float slopeAdditionalSpeed = _playerController.GetSlopeAdjustedAdditionalSpeed(movement, slopeHit.Value, additionalSpeed);
_playerController.Move(slopeMovement, deltaTime, slopeAdditionalSpeed);
}
else
{
_playerController.Move(movement, deltaTime, additionalSpeed);
}
if (movement.sqrMagnitude > 0.0001f)
_playerController.StepUp(movement);
}
private void OnDash()
{
if (_playerController.CanStartDash() && _playerController.TryStand())
_playerController.SwitchState(new DashingState(_playerController));
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
private void FaceMovementDirection(Vector3 movement, float deltaTime)
{
if (!_playerController.IsMovementFacingEnabled || movement.sqrMagnitude < 0.0001f)
return;
Vector3 planarMovement = Vector3.ProjectOnPlane(movement, Vector3.up);
if (planarMovement.sqrMagnitude < 0.0001f)
return;
Quaternion targetRotation = Quaternion.LookRotation(planarMovement.normalized, Vector3.up);
_playerController.RigidBody.MoveRotation(Quaternion.Slerp(
_playerController.RigidBody.rotation,
targetRotation,
_playerController.RotationDamping * deltaTime));
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: e41180b00431439cbfa57a4b96b24675
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/CrouchingState.cs
uploadId: 997018
@@ -0,0 +1,59 @@
using UnityEngine;
namespace CharacterMovement
{
public class DashingState : PlayerStateBase
{
private float _remainingDashTime;
public DashingState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Dashing");
_remainingDashTime = _playerController.DashDuration;
_playerController.DashCooldown = _playerController.DashCooldownDuration;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (_remainingDashTime <= 0f)
{
_playerController.SwitchState(new IdleState(_playerController));
return;
}
ExecuteDash(deltaTime);
}
public override void Exit()
{
}
private void ExecuteDash(float deltaTime)
{
float frameStepTime = Mathf.Min(deltaTime, _remainingDashTime);
_remainingDashTime -= deltaTime;
float dashSpeed = _playerController.DashLength / Mathf.Max(_playerController.DashDuration, 0.0001f);
float frameDistance = dashSpeed * frameStepTime;
Vector3 origin = _playerController.RigidBody.position;
Vector3 direction = _playerController.transform.forward;
Vector3 targetPosition = origin + direction * frameDistance;
if (Physics.Raycast(origin, direction, out RaycastHit hit, frameDistance,
_playerController.GroundLayerMask, QueryTriggerInteraction.Ignore))
{
targetPosition = hit.point + hit.normal * _playerController.CapsuleCollider.radius;
}
_playerController.RigidBody.MovePosition(targetPosition);
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 861825f6c8194d6587f63e5401792c49
timeCreated: 1701895502
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/DashingState.cs
uploadId: 997018
@@ -0,0 +1,58 @@
using UnityEngine;
namespace CharacterMovement
{
public class FallingState : PlayerStateBase
{
private Vector3 _airMomentum;
public FallingState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Falling");
_playerController.InputSource.DashPerformed += OnDash;
_airMomentum = _playerController.RigidBody.linearVelocity;
_airMomentum.y = 0f;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (_playerController.TryConsumeBufferedJump())
return;
if (_playerController.IsGrounded() && _playerController.RigidBody.linearVelocity.y <= 0f)
{
_playerController.SwitchState(new IdleState(_playerController));
return;
}
if (_playerController.CanMoveWhileJumping)
_airMomentum = _playerController.CalculateMovement();
_playerController.Move(_airMomentum, deltaTime, _playerController.GetAirborneAdditionalSpeed());
}
public override void Exit()
{
_playerController.InputSource.DashPerformed -= OnDash;
}
private void OnDash()
{
if (!_playerController.CanStartDash())
return;
_playerController.SwitchState(new DashingState(_playerController));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 28d356d32ce54e1aa9c731f333f826b7
timeCreated: 1701969322
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/FallingState.cs
uploadId: 997018
@@ -0,0 +1,72 @@
using UnityEngine;
namespace CharacterMovement
{
public class IdleState : PlayerStateBase, IGroundLocomotionState
{
public IdleState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Idle");
_playerController.FallingEvent += OnFalling;
_playerController.InputSource.DashPerformed += OnDash;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (_playerController.TryConsumeBufferedJump())
return;
if (_playerController.ShouldEnterAirborneState)
{
_playerController.SwitchState(new FallingState(_playerController));
return;
}
if (_playerController.IsGrounded())
_playerController.Move(Vector3.zero, deltaTime);
if (_playerController.CanMove && _playerController.InputSource.IsMoving && _playerController.IsGrounded())
{
_playerController.SwitchState(new MovingState(_playerController));
return;
}
RaycastHit? slopeHit = _playerController.OnSlope();
if (!slopeHit.HasValue)
return;
float slopeAngle = Vector3.Angle(slopeHit.Value.normal, Vector3.up);
if (slopeAngle > _playerController.MaxSlopeAngle)
_playerController.SwitchState(new SlidingState(_playerController, slopeHit));
}
public override void Exit()
{
_playerController.FallingEvent -= OnFalling;
_playerController.InputSource.DashPerformed -= OnDash;
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
private void OnDash()
{
if (!_playerController.CanStartDash())
return;
_playerController.SwitchState(new DashingState(_playerController));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 16ba794d3f644184897f17ab98a8fa69
timeCreated: 1701893368
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/IdleState.cs
uploadId: 997018
@@ -0,0 +1,83 @@
using UnityEngine;
namespace CharacterMovement
{
public class JumpingState : PlayerStateBase
{
private Vector3 _airMomentum;
public JumpingState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Jumping");
_playerController.FallingEvent += OnFalling;
_playerController.InputSource.DashPerformed += OnDash;
_airMomentum = _playerController.RigidBody.linearVelocity;
_airMomentum.y = 0f;
// A refused jump only means trouble when nothing else launched the character:
// skills such as double jump set the launch velocity themselves before entering here.
if (!_playerController.Jump(_playerController.JumpingForce)
&& _playerController.RigidBody.linearVelocity.y <= 0f)
{
_playerController.SwitchState(new FallingState(_playerController));
}
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
float verticalVelocity = _playerController.RigidBody.linearVelocity.y;
if (!_playerController.IsJumpGraceActive)
{
if (_playerController.IsGrounded() && verticalVelocity <= 0f)
{
_playerController.SwitchState(new IdleState(_playerController));
return;
}
if (verticalVelocity < 0f)
{
_playerController.SwitchState(new FallingState(_playerController));
return;
}
}
if (_playerController.CanMoveWhileJumping)
_airMomentum = _playerController.CalculateMovement();
_playerController.Move(_airMomentum, deltaTime, _playerController.GetAirborneAdditionalSpeed());
}
public override void Exit()
{
_playerController.FallingEvent -= OnFalling;
_playerController.InputSource.DashPerformed -= OnDash;
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
private void OnDash()
{
if (!_playerController.CanStartDash())
return;
float downwardBoost = _playerController.JumpingForce * _playerController.AirDashDownwardBoost;
if (downwardBoost > 0f)
_playerController.RigidBody.AddForce(Vector3.down * downwardBoost, ForceMode.VelocityChange);
_playerController.SwitchState(new DashingState(_playerController));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: a4d2b7e6880a4ef7bd56c121238969fe
timeCreated: 1701894885
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/JumpingState.cs
uploadId: 997018
@@ -0,0 +1,102 @@
using UnityEngine;
namespace CharacterMovement
{
public class MovingState : IdleState
{
public MovingState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Moving");
_playerController.FallingEvent += OnFalling;
_playerController.InputSource.DashPerformed += OnDash;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (_playerController.TryConsumeBufferedJump())
return;
if (!_playerController.CanMove || !_playerController.InputSource.IsMoving)
{
_playerController.SwitchState(new IdleState(_playerController));
return;
}
if (_playerController.ShouldEnterAirborneState)
{
_playerController.SwitchState(new FallingState(_playerController));
return;
}
Vector3 movement = _playerController.CalculateMovement();
float additionalSpeed = _playerController.GetInputTargetSpeed() - _playerController.Speed;
RaycastHit? slopeHit = _playerController.OnSlope();
if (slopeHit != null)
{
float slopeAngle = Vector3.Angle(slopeHit.Value.normal, Vector3.up);
if (slopeAngle > _playerController.MaxSlopeAngle)
{
_playerController.SwitchState(new SlidingState(_playerController, slopeHit));
return;
}
Vector3 slopeMovement = Vector3.ProjectOnPlane(movement, slopeHit.Value.normal).normalized;
float slopeAdditionalSpeed = _playerController.GetSlopeAdjustedAdditionalSpeed(movement, slopeHit.Value, additionalSpeed);
_playerController.Move(slopeMovement, deltaTime, slopeAdditionalSpeed);
}
else
{
_playerController.Move(movement, deltaTime, additionalSpeed);
}
_playerController.StepUp(movement);
if (_playerController.IsMovementFacingEnabled)
FaceMovementDirection(movement, deltaTime);
}
public override void Exit()
{
_playerController.InputSource.DashPerformed -= OnDash;
_playerController.FallingEvent -= OnFalling;
}
private void OnDash()
{
if (!_playerController.CanStartDash())
return;
_playerController.SwitchState(new DashingState(_playerController));
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
private void FaceMovementDirection(Vector3 movement, float deltaTime)
{
if (movement.sqrMagnitude < 0.0001f)
return;
Vector3 planarMovement = Vector3.ProjectOnPlane(movement, Vector3.up);
if (planarMovement.sqrMagnitude < 0.0001f)
return;
Quaternion targetRotation = Quaternion.LookRotation(planarMovement.normalized, Vector3.up);
_playerController.RigidBody.MoveRotation(Quaternion.Slerp(
_playerController.RigidBody.rotation,
targetRotation,
_playerController.RotationDamping * deltaTime));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 2092358afbf4419da802856b697337ca
timeCreated: 1701894196
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/MovingState.cs
uploadId: 997018
@@ -0,0 +1,92 @@
using UnityEngine;
namespace CharacterMovement
{
public class PlayerSlideState : PlayerStateBase, IGroundLocomotionState
{
private Vector3 _slideDirection;
private float _elapsedTime;
public PlayerSlideState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Sliding");
_playerController.SlideCooldown = _playerController.SlideCooldownDuration;
_playerController.SetTemporaryCapsuleHeight(_playerController.CrouchCapsuleHeight);
_slideDirection = ResolveSlideDirection();
Vector3 velocity = _playerController.RigidBody.linearVelocity;
_playerController.RigidBody.linearVelocity = new Vector3(
_slideDirection.x * _playerController.SlideStartSpeed,
velocity.y,
_slideDirection.z * _playerController.SlideStartSpeed);
_playerController.FallingEvent += OnFalling;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (!_playerController.IsGrounded())
{
_playerController.SwitchState(new FallingState(_playerController));
return;
}
_elapsedTime += deltaTime;
float normalized = Mathf.Clamp01(_elapsedTime / Mathf.Max(0.01f, _playerController.SlideDuration));
Vector3 inputDirection = _playerController.CalculateMovement();
if (inputDirection.sqrMagnitude > 0.0001f)
{
_slideDirection = Vector3.Slerp(
_slideDirection,
Vector3.ProjectOnPlane(inputDirection, Vector3.up).normalized,
_playerController.SlideSteeringStrength * deltaTime).normalized;
}
float speed = Mathf.Lerp(_playerController.SlideStartSpeed, _playerController.SlideEndSpeed, normalized);
_playerController.Move(_slideDirection, deltaTime, speed - _playerController.Speed);
if (normalized >= 1f || !_playerController.InputSource.IsCrouching)
{
if (_playerController.InputSource.IsCrouching)
_playerController.TryCrouch();
else
_playerController.TryStand();
_playerController.SwitchToBaseGroundLocomotion();
}
}
public override void Exit()
{
_playerController.FallingEvent -= OnFalling;
if (!_playerController.InputSource.IsCrouching && _playerController.CurrentStance == PlayerStance.Standing)
_playerController.SetTemporaryCapsuleHeight(_playerController.OriginalCapsuleHeight);
}
private Vector3 ResolveSlideDirection()
{
Vector3 velocity = Vector3.ProjectOnPlane(_playerController.RigidBody.linearVelocity, Vector3.up);
if (velocity.sqrMagnitude > 0.0001f)
return velocity.normalized;
Vector3 movement = _playerController.CalculateMovement();
if (movement.sqrMagnitude > 0.0001f)
return Vector3.ProjectOnPlane(movement, Vector3.up).normalized;
return Vector3.ProjectOnPlane(_playerController.transform.forward, Vector3.up).normalized;
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 1c30feb7606f44a9b700f906d041c718
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/PlayerSlideState.cs
uploadId: 997018
@@ -0,0 +1,70 @@
using UnityEngine;
namespace CharacterMovement
{
public class ProneState : PlayerStateBase, IGroundLocomotionState
{
public ProneState(PlayerController playerController) : base(playerController)
{
}
public override void Enter()
{
_playerController.SetStateLabel("Prone");
_playerController.TryProne();
_playerController.FallingEvent += OnFalling;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
if (_playerController.HasBufferedJumpIntent && _playerController.TryStand() && _playerController.TryConsumeBufferedJump())
return;
if (!_playerController.IsGrounded())
{
_playerController.SwitchState(new FallingState(_playerController));
return;
}
Vector3 movement = _playerController.CalculateMovement();
float additionalSpeed = _playerController.ProneSpeed - _playerController.Speed;
_playerController.Move(movement, deltaTime, additionalSpeed);
if (_playerController.CanMove && _playerController.InputSource.IsMoving)
FaceMovementDirection(movement, deltaTime);
if (!_playerController.InputSource.IsProne && _playerController.TryStand())
_playerController.SwitchToBaseGroundLocomotion();
}
public override void Exit()
{
_playerController.FallingEvent -= OnFalling;
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
private void FaceMovementDirection(Vector3 movement, float deltaTime)
{
if (!_playerController.IsMovementFacingEnabled || movement.sqrMagnitude < 0.0001f)
return;
Vector3 planarMovement = Vector3.ProjectOnPlane(movement, Vector3.up);
if (planarMovement.sqrMagnitude < 0.0001f)
return;
Quaternion targetRotation = Quaternion.LookRotation(planarMovement.normalized, Vector3.up);
_playerController.RigidBody.MoveRotation(Quaternion.Slerp(
_playerController.RigidBody.rotation,
targetRotation,
_playerController.RotationDamping * deltaTime));
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: bb6cc48500004169b81e8bc56f8819c2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/ProneState.cs
uploadId: 997018
@@ -0,0 +1,65 @@
using UnityEngine;
namespace CharacterMovement
{
public class SlidingState : PlayerStateBase
{
private RaycastHit _currentSlopeHit;
public SlidingState(PlayerController playerController, RaycastHit? slopeHit) : base(playerController)
{
if (slopeHit.HasValue)
_currentSlopeHit = slopeHit.Value;
}
public override void Enter()
{
_playerController.SetStateLabel("Sliding");
_playerController.FallingEvent += OnFalling;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
RaycastHit? slopeHit = _playerController.OnSlope();
if (!slopeHit.HasValue)
{
_playerController.SwitchState(new IdleState(_playerController));
return;
}
_currentSlopeHit = slopeHit.Value;
float slopeAngle = Vector3.Angle(_currentSlopeHit.normal, Vector3.up);
if (slopeAngle <= _playerController.MaxSlopeAngle)
{
_playerController.SwitchState(new IdleState(_playerController));
return;
}
_playerController.SlideDownSlope(_currentSlopeHit.normal);
float maxSlideSpeed = _playerController.MaxSlopeSlideSpeed;
Vector3 velocity = _playerController.RigidBody.linearVelocity;
Vector3 horizontalVelocity = new Vector3(velocity.x, 0f, velocity.z);
if (maxSlideSpeed > 0f && horizontalVelocity.sqrMagnitude > maxSlideSpeed * maxSlideSpeed)
{
horizontalVelocity = horizontalVelocity.normalized * maxSlideSpeed;
_playerController.RigidBody.linearVelocity =
new Vector3(horizontalVelocity.x, velocity.y, horizontalVelocity.z);
}
}
public override void Exit()
{
_playerController.FallingEvent -= OnFalling;
}
private void OnFalling()
{
_playerController.SwitchState(new FallingState(_playerController));
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 7c99189efcc74ea793859c4773dd8d3d
timeCreated: 1702940353
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/SlidingState.cs
uploadId: 997018
@@ -0,0 +1,60 @@
using UnityEngine;
namespace CharacterMovement
{
public class VaultingState : PlayerStateBase
{
private readonly VaultTarget _target;
private float _elapsedTime;
public VaultingState(PlayerController playerController, VaultTarget target) : base(playerController)
{
_target = target;
}
public override void Enter()
{
_playerController.SetStateLabel("Vaulting");
_playerController.VaultCooldown = _playerController.VaultCooldownDuration;
_playerController.TryStand();
_playerController.RigidBody.linearVelocity = Vector3.zero;
}
public override void UpdateState(float deltaTime)
{
}
public override void FixedUpdateState(float deltaTime)
{
_elapsedTime += deltaTime;
float normalized = Mathf.Clamp01(_elapsedTime / Mathf.Max(0.01f, _playerController.VaultDuration));
float eased = Mathf.SmoothStep(0f, 1f, normalized);
Vector3 position = Vector3.Lerp(_target.StartPosition, _target.EndPosition, eased);
position += Vector3.up * (Mathf.Sin(normalized * Mathf.PI) * _playerController.VaultArcHeight);
_playerController.RigidBody.MovePosition(position);
FaceVaultDirection(deltaTime);
if (normalized >= 1f)
_playerController.SwitchToBaseGroundLocomotion();
}
public override void Exit()
{
_playerController.RigidBody.linearVelocity = Vector3.zero;
}
private void FaceVaultDirection(float deltaTime)
{
Vector3 planarDirection = Vector3.ProjectOnPlane(_target.TravelDirection, Vector3.up);
if (!_playerController.IsMovementFacingEnabled || planarDirection.sqrMagnitude < 0.0001f)
return;
Quaternion targetRotation = Quaternion.LookRotation(planarDirection.normalized, Vector3.up);
_playerController.RigidBody.MoveRotation(Quaternion.Slerp(
_playerController.RigidBody.rotation,
targetRotation,
_playerController.RotationDamping * deltaTime));
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 836df6c8889d4a07906eac99e89a6503
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Actions/VaultingState.cs
uploadId: 997018
@@ -0,0 +1,208 @@
using UnityEngine;
namespace CharacterMovement
{
internal sealed class CharacterGroundProbe
{
/// <summary>
/// Finds the surface supporting the capsule.
/// The returned hit distance is normalised to the vertical gap between the capsule's foot
/// plane and the surface, so every caller measures ground clearance the same way regardless
/// of which probe produced the hit.
/// </summary>
public bool TryGetSurfaceHit(
Transform characterTransform,
CapsuleCollider capsule,
LayerMask probeMask,
float radiusScale,
float groundCheckDistance,
float extraDistance,
float epsilon,
float liftOffset,
bool useSupplementaryRays,
float supplementaryRaySpread,
out RaycastHit bestHit,
ref GroundProbeDebugData debugData)
{
bestHit = default;
Vector3 up = characterTransform.up;
Vector3 center = characterTransform.TransformPoint(capsule.center);
float castRadius = Mathf.Max(0.01f, capsule.radius * radiusScale);
float halfHeight = Mathf.Max(capsule.height * 0.5f, castRadius);
float halfSegment = Mathf.Max(0f, halfHeight - castRadius);
float maxGroundDistance = Mathf.Max(0.01f, groundCheckDistance + extraDistance);
Vector3 footPoint = center - up * halfHeight;
Vector3 topPoint = center + up * (halfSegment + liftOffset);
Vector3 bottomPoint = center - up * (halfSegment - liftOffset);
debugData.CapsuleTop = topPoint;
debugData.CapsuleBottom = bottomPoint;
debugData.CapsuleCastRadius = castRadius;
debugData.CapsuleCastDistance = maxGroundDistance + liftOffset;
debugData.SupplementaryRayCount = 0;
bool hasHit = false;
if (Physics.CapsuleCast(
topPoint,
bottomPoint,
castRadius,
Vector3.down,
out RaycastHit capsuleHit,
maxGroundDistance + liftOffset,
probeMask,
QueryTriggerInteraction.Ignore))
{
TryAcceptCandidate(capsuleHit, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit);
}
if (!useSupplementaryRays)
{
debugData.HasSurfaceHit = hasHit;
if (hasHit)
{
debugData.SurfaceHit = bestHit;
debugData.SlopeAngle = Vector3.Angle(bestHit.normal, Vector3.up);
}
return hasHit;
}
float fullRayDistance = halfHeight + maxGroundDistance + epsilon;
TrySupplementaryRay(center, fullRayDistance, probeMask, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit, ref debugData);
TrySupplementaryRay(center + Vector3.up * (castRadius * 0.5f), fullRayDistance + castRadius * 0.5f, probeMask, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit, ref debugData);
float offset = castRadius * Mathf.Max(0f, supplementaryRaySpread);
Vector3 worldForward = Vector3.ProjectOnPlane(characterTransform.forward, Vector3.up).normalized;
if (worldForward.sqrMagnitude > 0.0001f)
{
Vector3 worldRight = Vector3.Cross(worldForward, Vector3.up);
TrySupplementaryRay(center + worldForward * offset, fullRayDistance, probeMask, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit, ref debugData);
TrySupplementaryRay(center - worldForward * offset, fullRayDistance, probeMask, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit, ref debugData);
TrySupplementaryRay(center + worldRight * offset, fullRayDistance, probeMask, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit, ref debugData);
TrySupplementaryRay(center - worldRight * offset, fullRayDistance, probeMask, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit, ref debugData);
}
debugData.HasSurfaceHit = hasHit;
if (hasHit)
{
debugData.SurfaceHit = bestHit;
debugData.SlopeAngle = Vector3.Angle(bestHit.normal, Vector3.up);
}
return hasHit;
}
private static void TrySupplementaryRay(
Vector3 origin,
float distance,
LayerMask mask,
Transform characterTransform,
Vector3 footPoint,
Vector3 up,
float maxGroundDistance,
ref RaycastHit bestHit,
ref bool hasHit,
ref GroundProbeDebugData debugData)
{
int debugIndex = debugData.SupplementaryRayCount;
if (debugIndex < GroundProbeDebugData.MaxSupplementaryRays)
{
debugData.SupplementaryRayOrigins[debugIndex] = origin;
debugData.SupplementaryRayDirections[debugIndex] = Vector3.down;
debugData.SupplementaryRayDistances[debugIndex] = distance;
debugData.SupplementaryRayHits[debugIndex] = false;
debugData.SupplementaryRayCount++;
}
if (!Physics.Raycast(origin, Vector3.down, out RaycastHit hit, distance, mask, QueryTriggerInteraction.Ignore))
return;
if (debugIndex < GroundProbeDebugData.MaxSupplementaryRays)
{
debugData.SupplementaryRayHits[debugIndex] = true;
debugData.SupplementaryRayHitInfos[debugIndex] = hit;
}
TryAcceptCandidate(hit, characterTransform, footPoint, up, maxGroundDistance, ref bestHit, ref hasHit);
}
/// <summary>
/// Rewrites the hit distance as the vertical gap below the foot plane and keeps the
/// candidate only when that gap is inside the allowed ground range.
/// </summary>
private static void TryAcceptCandidate(
RaycastHit hit,
Transform characterTransform,
Vector3 footPoint,
Vector3 up,
float maxGroundDistance,
ref RaycastHit bestHit,
ref bool hasHit)
{
// Weapons, hitboxes and other child colliders are part of the character, not the floor.
// Without this a child collider on a ground layer would report the character as standing
// on itself, which never resolves.
if (IsSelfCollider(hit.collider, characterTransform))
return;
float footDistance = Vector3.Dot(footPoint - hit.point, up);
if (footDistance > maxGroundDistance)
return;
hit.distance = Mathf.Max(0f, footDistance);
if (!hasHit || hit.normal.y > bestHit.normal.y)
{
bestHit = hit;
hasHit = true;
}
}
private static bool IsSelfCollider(Collider hitCollider, Transform characterTransform)
{
if (!hitCollider || !characterTransform)
return false;
Transform hitTransform = hitCollider.transform;
return hitTransform == characterTransform || hitTransform.IsChildOf(characterTransform);
}
}
internal struct GroundProbeDebugData
{
public const int MaxSupplementaryRays = 8;
public bool HasSurfaceHit;
public RaycastHit SurfaceHit;
public float SlopeAngle;
public Vector3 CapsuleTop;
public Vector3 CapsuleBottom;
public float CapsuleCastRadius;
public float CapsuleCastDistance;
public readonly Vector3[] SupplementaryRayOrigins;
public readonly Vector3[] SupplementaryRayDirections;
public readonly float[] SupplementaryRayDistances;
public readonly bool[] SupplementaryRayHits;
public readonly RaycastHit[] SupplementaryRayHitInfos;
public int SupplementaryRayCount;
public GroundProbeDebugData(int maxRays)
{
HasSurfaceHit = false;
SurfaceHit = default;
SlopeAngle = 0f;
CapsuleTop = Vector3.zero;
CapsuleBottom = Vector3.zero;
CapsuleCastRadius = 0f;
CapsuleCastDistance = 0f;
SupplementaryRayOrigins = new Vector3[maxRays];
SupplementaryRayDirections = new Vector3[maxRays];
SupplementaryRayDistances = new float[maxRays];
SupplementaryRayHits = new bool[maxRays];
SupplementaryRayHitInfos = new RaycastHit[maxRays];
SupplementaryRayCount = 0;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 0f89ae7647fc4087b2e39bf1a1da8b04
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/CharacterGroundProbe.cs
uploadId: 997018
@@ -0,0 +1,257 @@
using UnityEngine;
namespace CharacterMovement
{
/// <summary>
/// A reusable movement feel preset. Assign one to <see cref="PlayerController.MotorSettings"/> to
/// drive that character's tuning from a shared asset instead of per-instance values.
/// </summary>
/// <remarks>
/// The controller copies these values on validate and on start, so editing the asset re-feels
/// every character using it.
/// <para>
/// A preset describes how movement <i>feels</i>: speeds, acceleration, the jump arc, gravity,
/// and the probe tuning underneath them. It deliberately does not describe which abilities a
/// character has, or whether sprint is hold or toggle. Because a preset overwrites the
/// controller every time it validates, anything stored here can never be overridden per
/// character — so those choices stay on <see cref="PlayerController"/> where a designer can
/// actually make them.
/// </para>
/// </remarks>
[CreateAssetMenu(menuName = "Character Controller/Core/Character Motor Settings", fileName = "CharacterMotorSettings")]
public class CharacterMotorSettings : ScriptableObject
{
[Header("Movement Speeds")]
[SerializeField, Min(0f)] private float runSpeed = 5f;
[Tooltip("Target speed while sprinting. An absolute speed, not a bonus added to Run Speed.")]
[SerializeField, Min(0f)] private float sprintSpeed = 8f;
[Tooltip("Target speed while the walk modifier is held.")]
[SerializeField, Min(0f)] private float walkSpeed = 2f;
[Tooltip("Target speed while crouched.")]
[SerializeField, Min(0f)] private float crouchSpeed = 2.4f;
[Tooltip("Target speed while prone.")]
[SerializeField, Min(0f)] private float proneSpeed = 1.2f;
[Header("Acceleration")]
[Tooltip("How quickly the character reaches its target speed, in m/s squared.")]
[SerializeField, Min(0f)] private float groundAcceleration = 38f;
[Tooltip("How quickly the character slows when input stops, in m/s squared.")]
[SerializeField, Min(0f)] private float groundDeceleration = 44f;
[Tooltip("How quickly the character reaches its target speed while airborne.")]
[SerializeField, Min(0f)] private float airAcceleration = 12f;
[Tooltip("How quickly airborne speed bleeds off with no input. Low values preserve jump momentum.")]
[SerializeField, Min(0f)] private float airDeceleration = 2f;
[Header("Jump And Fall")]
[SerializeField, Min(0f)]
[Tooltip("Upward speed applied at launch, in m/s.")]
private float jumpingForce = 8f;
[SerializeField]
[Tooltip("Releasing the jump button while rising cuts the jump short, giving tap-versus-hold "
+ "height control.")]
private bool variableJumpHeight = true;
[SerializeField, Range(0.05f, 1f)]
[Tooltip("How much upward speed survives an early jump release. 1 disables the cut.")]
private float jumpCutMultiplier = 0.5f;
[SerializeField, Min(1f)]
[Tooltip("Extra gravity while falling, on top of Gravity Scale. Above 1 makes descents feel "
+ "weightier than ascents.")]
private float fallGravityMultiplier = 1f;
[SerializeField] private bool canMoveWhileJumping = true;
[Tooltip("Grace period after walking off a ledge during which a jump still works.")]
[SerializeField, Min(0f)] private float coyoteTime = 0.15f;
[Tooltip("How long a jump press is remembered so it can fire on landing.")]
[SerializeField, Min(0f)] private float jumpBufferTime = 0.12f;
[Tooltip("How long a jump press stays available to traversal actions such as vaulting.")]
[SerializeField, Min(0f)] private float parkourBufferTime = 0.12f;
[SerializeField, Min(0.01f)] private float gravityScale = 1f;
[SerializeField, Min(0f)] private float maxFallSpeed = 28f;
[SerializeField, Min(0f)]
[Tooltip("Protected window right after launch where ground stick, ground snapping and coyote "
+ "refresh stay off so the jump cannot be cancelled by nearby ground.")]
private float jumpGraceDuration = 0.08f;
[Header("Stance")]
[Tooltip("Capsule height while crouched.")]
[SerializeField, Min(0.1f)] private float crouchCapsuleHeight = 1.15f;
[Tooltip("Capsule height while prone.")]
[SerializeField, Min(0.1f)] private float proneCapsuleHeight = 0.55f;
[Tooltip("How fast the capsule resizes between stances. 0 snaps instantly.")]
[SerializeField, Min(0f)] private float stanceTransitionSpeed = 14f;
[Header("Slide")]
[Tooltip("How long a slide lasts before returning to normal locomotion.")]
[SerializeField, Min(0.05f)] private float slideDuration = 0.75f;
[Tooltip("Speed at the start of a slide.")]
[SerializeField, Min(0f)] private float slideStartSpeed = 9f;
[Tooltip("Speed at the end of a slide.")]
[SerializeField, Min(0f)] private float slideEndSpeed = 2.5f;
[Tooltip("How much the player can steer mid-slide. 0 locks the direction.")]
[SerializeField, Min(0f)] private float slideSteeringStrength = 0.35f;
[SerializeField, Min(0f)] private float slideCooldownDuration = 0.5f;
[SerializeField, Min(0f)] private float minimumSlideInputSpeed = 5.5f;
[SerializeField, Min(0f)]
[Tooltip("Speed cap while sliding down a slope too steep to stand on.")]
private float maxSlopeSlideSpeed = 10f;
[Header("Ground And Slopes")]
[Tooltip("Steepest surface the character can stand and walk on.")]
[SerializeField, Range(0f, 90f)] private float maxSlopeAngle = 45f;
[Tooltip("Steepest walkable angle for colliders on the Stairs layer.")]
[SerializeField, Range(0f, 90f)] private float maxStairsAngle = 60f;
[Tooltip("Ground probe width as a fraction of the capsule radius.")]
[SerializeField, Range(0.5f, 1f)] private float groundProbeRadiusScale = 0.95f;
[Tooltip("How far below the feet still counts as grounded.")]
[SerializeField, Min(0.01f)] private float groundCheckDistance = 0.15f;
[Tooltip("How far the character is pulled down to stay attached over crests and down stairs. 0 "
+ "disables snapping.")]
[SerializeField, Min(0f)] private float groundSnapDistance = 0.18f;
[Tooltip("Downward acceleration while grounded that keeps contact on slopes and platforms. Never "
+ "applied while rising.")]
[SerializeField, Min(0f)] private float groundStickForce = 24f;
[Tooltip("Tallest step the character can climb without jumping.")]
[SerializeField, Min(0.01f)] private float stepHeight = 0.35f;
[Tooltip("How far ahead to look for a step.")]
[SerializeField, Min(0.01f)] private float stepCheckDistance = 0.2f;
[SerializeField, Range(0.1f, 1f)] private float stepProbeRadiusScale = 0.85f;
[SerializeField, Min(0f)] private float ceilingCheckDistance = 0.05f;
[SerializeField, Range(0.5f, 1f)]
[Tooltip("Width of the ceiling probe as a fraction of the capsule radius.")]
private float ceilingProbeRadiusScale = 0.95f;
[SerializeField, Range(0.5f, 1f)]
[Tooltip("Width of the stand-up clearance check as a fraction of the capsule radius.")]
private float stanceClearanceRadiusScale = 0.95f;
[SerializeField]
[Tooltip("Casts extra downward rays as well as the main sweep, keeping footing on grates, "
+ "stair noses and narrow ledges.")]
private bool useSupplementaryGroundRays = true;
[SerializeField, Range(0f, 1f)]
[Tooltip("How far the supplementary rays sit from the capsule centre, as a fraction of the "
+ "probe radius.")]
private float supplementaryRaySpread = 0.3f;
[SerializeField, Min(0f)]
[Tooltip("How far the ground probe starts above the capsule before sweeping down.")]
private float groundProbeLiftOffset = 0.05f;
[SerializeField, Min(0f)]
[Tooltip("Extra reach added to the probe rays, absorbing float error at contact.")]
private float groundProbeEpsilon = 0.05f;
[SerializeField, Range(0.1f, 2f)] private float uphillSlopeSpeedMultiplier = 0.9f;
[SerializeField, Range(0.1f, 2f)] private float downhillSlopeSpeedMultiplier = 1.05f;
[Tooltip("Acceleration pulling the character down slopes steeper than Max Slope Angle.")]
[SerializeField, Min(0f)] private float slideForce = 15f;
[Tooltip("How fast the character tilts toward the slope normal.")]
[SerializeField, Min(0f)] private float slopeAlignment = 5f;
[Tooltip("Tilts the character to match the slope it stands on. Suits third-person characters; "
+ "usually off for first-person.")]
[SerializeField] private bool alignToSlopeNormal = true;
[Header("External Forces")]
[SerializeField, Min(0f)] private float externalForceDrag = 5f;
[SerializeField, Min(0f)]
[Tooltip("Upward speed above which a grounded character is considered launched and hands "
+ "over to the airborne state immediately.")]
private float airborneLaunchVelocityThreshold = 0.1f;
[SerializeField, Min(0f)]
[Tooltip("Downward speed below which the character is considered to be falling.")]
private float fallDetectionVelocityThreshold = 0.05f;
public float RunSpeed => runSpeed;
public float SprintSpeed => sprintSpeed;
public float WalkSpeed => walkSpeed;
public float CrouchSpeed => crouchSpeed;
public float ProneSpeed => proneSpeed;
public float GroundAcceleration => groundAcceleration;
public float GroundDeceleration => groundDeceleration;
public float AirAcceleration => airAcceleration;
public float AirDeceleration => airDeceleration;
public float JumpingForce => jumpingForce;
public bool VariableJumpHeight => variableJumpHeight;
public float JumpCutMultiplier => jumpCutMultiplier;
public float FallGravityMultiplier => fallGravityMultiplier;
public bool CanMoveWhileJumping => canMoveWhileJumping;
public float CoyoteTime => coyoteTime;
public float JumpBufferTime => jumpBufferTime;
public float ParkourBufferTime => parkourBufferTime;
public float GravityScale => gravityScale;
public float MaxFallSpeed => maxFallSpeed;
public float JumpGraceDuration => jumpGraceDuration;
public float CrouchCapsuleHeight => crouchCapsuleHeight;
public float ProneCapsuleHeight => proneCapsuleHeight;
public float StanceTransitionSpeed => stanceTransitionSpeed;
public float SlideDuration => slideDuration;
public float SlideStartSpeed => slideStartSpeed;
public float SlideEndSpeed => slideEndSpeed;
public float SlideSteeringStrength => slideSteeringStrength;
public float SlideCooldownDuration => slideCooldownDuration;
public float MinimumSlideInputSpeed => minimumSlideInputSpeed;
public float MaxSlopeSlideSpeed => maxSlopeSlideSpeed;
public float MaxSlopeAngle => maxSlopeAngle;
public float MaxStairsAngle => maxStairsAngle;
public float GroundProbeRadiusScale => groundProbeRadiusScale;
public float GroundCheckDistance => groundCheckDistance;
public float GroundSnapDistance => groundSnapDistance;
public float GroundStickForce => groundStickForce;
public float StepHeight => stepHeight;
public float StepCheckDistance => stepCheckDistance;
public float StepProbeRadiusScale => stepProbeRadiusScale;
public float CeilingCheckDistance => ceilingCheckDistance;
public float CeilingProbeRadiusScale => ceilingProbeRadiusScale;
public float StanceClearanceRadiusScale => stanceClearanceRadiusScale;
public bool UseSupplementaryGroundRays => useSupplementaryGroundRays;
public float SupplementaryRaySpread => supplementaryRaySpread;
public float GroundProbeLiftOffset => groundProbeLiftOffset;
public float GroundProbeEpsilon => groundProbeEpsilon;
public float UphillSlopeSpeedMultiplier => uphillSlopeSpeedMultiplier;
public float DownhillSlopeSpeedMultiplier => downhillSlopeSpeedMultiplier;
public float SlideForce => slideForce;
public float SlopeAlignment => slopeAlignment;
public bool AlignToSlopeNormal => alignToSlopeNormal;
public float ExternalForceDrag => externalForceDrag;
public float AirborneLaunchVelocityThreshold => airborneLaunchVelocityThreshold;
public float FallDetectionVelocityThreshold => fallDetectionVelocityThreshold;
private void OnValidate()
{
runSpeed = Mathf.Max(0f, runSpeed);
sprintSpeed = Mathf.Max(0f, sprintSpeed);
walkSpeed = Mathf.Max(0f, walkSpeed);
crouchSpeed = Mathf.Max(0f, crouchSpeed);
proneSpeed = Mathf.Max(0f, proneSpeed);
groundAcceleration = Mathf.Max(0f, groundAcceleration);
groundDeceleration = Mathf.Max(0f, groundDeceleration);
airAcceleration = Mathf.Max(0f, airAcceleration);
airDeceleration = Mathf.Max(0f, airDeceleration);
jumpingForce = Mathf.Max(0f, jumpingForce);
jumpCutMultiplier = Mathf.Clamp(jumpCutMultiplier, 0.05f, 1f);
fallGravityMultiplier = Mathf.Max(1f, fallGravityMultiplier);
coyoteTime = Mathf.Max(0f, coyoteTime);
jumpBufferTime = Mathf.Max(0f, jumpBufferTime);
parkourBufferTime = Mathf.Max(0f, parkourBufferTime);
gravityScale = Mathf.Max(0.01f, gravityScale);
maxFallSpeed = Mathf.Max(0f, maxFallSpeed);
crouchCapsuleHeight = Mathf.Max(0.1f, crouchCapsuleHeight);
proneCapsuleHeight = Mathf.Max(0.1f, proneCapsuleHeight);
stanceTransitionSpeed = Mathf.Max(0f, stanceTransitionSpeed);
slideDuration = Mathf.Max(0.05f, slideDuration);
slideStartSpeed = Mathf.Max(0f, slideStartSpeed);
slideEndSpeed = Mathf.Max(0f, slideEndSpeed);
slideSteeringStrength = Mathf.Max(0f, slideSteeringStrength);
slideCooldownDuration = Mathf.Max(0f, slideCooldownDuration);
minimumSlideInputSpeed = Mathf.Max(0f, minimumSlideInputSpeed);
groundSnapDistance = Mathf.Max(0f, groundSnapDistance);
groundStickForce = Mathf.Max(0f, groundStickForce);
stepHeight = Mathf.Max(0.01f, stepHeight);
stepCheckDistance = Mathf.Max(0.01f, stepCheckDistance);
ceilingCheckDistance = Mathf.Max(0f, ceilingCheckDistance);
slideForce = Mathf.Max(0f, slideForce);
slopeAlignment = Mathf.Max(0f, slopeAlignment);
externalForceDrag = Mathf.Max(0f, externalForceDrag);
jumpGraceDuration = Mathf.Max(0f, jumpGraceDuration);
maxSlopeSlideSpeed = Mathf.Max(0f, maxSlopeSlideSpeed);
groundProbeLiftOffset = Mathf.Max(0f, groundProbeLiftOffset);
groundProbeEpsilon = Mathf.Max(0f, groundProbeEpsilon);
airborneLaunchVelocityThreshold = Mathf.Max(0f, airborneLaunchVelocityThreshold);
fallDetectionVelocityThreshold = Mathf.Max(0f, fallDetectionVelocityThreshold);
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: f6f5dbdbb9e844948b4a51538e11f142
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/CharacterMotorSettings.cs
uploadId: 997018
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e910d470874d45d48ef952251c74031b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,91 @@
using UnityEngine;
namespace CharacterMovement
{
/// <summary>
/// The accumulator every registered <see cref="ICharacterMovementModifier"/> writes into.
/// </summary>
/// <remarks>
/// Speed contributions multiply and capability blocks combine, so the result does not depend on
/// the order modifiers were registered in. Modifiers can only restrict movement: there is no way
/// to re-allow something another modifier blocked, which keeps the combined result predictable
/// when several unrelated systems are active at once.
/// </remarks>
public struct CharacterMovementModifiers
{
private float _speedMultiplier;
private MovementCapability _blockedCapabilities;
private CharacterMovementModifiers(float speedMultiplier, MovementCapability blockedCapabilities)
{
_speedMultiplier = speedMultiplier;
_blockedCapabilities = blockedCapabilities;
}
/// <summary>An unrestricted result: full speed, nothing blocked.</summary>
public static CharacterMovementModifiers Unrestricted =>
new CharacterMovementModifiers(1f, MovementCapability.None);
/// <summary>The combined speed scale, where 1 is the controller's configured speed.</summary>
public float SpeedMultiplier => _speedMultiplier;
/// <summary>Every capability at least one modifier denied.</summary>
public MovementCapability BlockedCapabilities => _blockedCapabilities;
/// <summary>Scales the movement speed. Negative values are treated as zero.</summary>
public void MultiplySpeed(float multiplier)
{
_speedMultiplier *= Mathf.Max(0f, multiplier);
}
/// <summary>Denies one or more capabilities for as long as this modifier is registered.</summary>
public void Block(MovementCapability capabilities)
{
_blockedCapabilities |= capabilities;
}
/// <summary>True when every capability in <paramref name="capabilities"/> is still allowed.</summary>
public bool IsAllowed(MovementCapability capabilities)
{
return (_blockedCapabilities & capabilities) == MovementCapability.None;
}
}
/// <summary>
/// Lets a gameplay system influence locomotion without modifying the controller.
/// </summary>
/// <remarks>
/// Register with <see cref="PlayerController.AddMovementModifier"/>. The controller re-evaluates
/// every registered modifier once per update and once per physics step, so implementations should
/// be cheap and side-effect free — read your own state, write to the accumulator, return.
/// <para>
/// For the common case of a value some other code toggles, use
/// <see cref="PlayerController.CreateMovementModifier"/> to get a ready-made
/// <see cref="MovementModifierHandle"/> instead of implementing this interface.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // An RPG stamina component denying sprint while exhausted.
/// public class StaminaSprintGate : MonoBehaviour, ICharacterMovementModifier
/// {
/// [SerializeField] private PlayerController controller;
/// [SerializeField] private Stamina stamina;
///
/// private void OnEnable() =&gt; controller.AddMovementModifier(this);
/// private void OnDisable() =&gt; controller.RemoveMovementModifier(this);
///
/// public void ApplyMovementModifiers(ref CharacterMovementModifiers modifiers)
/// {
/// if (stamina.Current &lt;= 0f)
/// modifiers.Block(MovementCapability.Sprint);
/// }
/// }
/// </code>
/// </example>
public interface ICharacterMovementModifier
{
/// <summary>Contributes this system's restrictions to the combined result.</summary>
void ApplyMovementModifiers(ref CharacterMovementModifiers modifiers);
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 851a564018bc4dc7aa2f2f51599eaf06
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Extensibility/ICharacterMovementModifier.cs
uploadId: 997018
@@ -0,0 +1,57 @@
namespace CharacterMovement
{
/// <summary>
/// The controller's locomotion state, as seen from outside.
/// </summary>
/// <remarks>
/// This is the stable contract other systems should read and switch on. The internal
/// <see cref="State"/> classes are an implementation detail and may change between versions;
/// this enum will not. Read it from <see cref="PlayerController.MovementState"/> and subscribe to
/// <see cref="PlayerController.MovementStateChanged"/>.
/// <para>
/// Deliberately limited to locomotion. Combat, aiming, casting and similar gameplay states belong
/// to the systems that own them, not to the character motor.
/// </para>
/// </remarks>
public enum LocomotionState
{
/// <summary>No controller state is active yet (before the first frame).</summary>
None = 0,
/// <summary>Grounded and not moving.</summary>
Idle = 1,
/// <summary>Grounded and moving at walk speed.</summary>
Walking = 2,
/// <summary>Grounded and moving at the default run speed.</summary>
Running = 3,
/// <summary>Grounded and moving at sprint speed.</summary>
Sprinting = 4,
/// <summary>Grounded in the crouch stance.</summary>
Crouching = 5,
/// <summary>Grounded in the prone stance.</summary>
Prone = 6,
/// <summary>Airborne and moving upward after a jump.</summary>
Jumping = 7,
/// <summary>Airborne and moving downward.</summary>
Falling = 8,
/// <summary>Sliding, either an input slide or an involuntary steep-slope slide.</summary>
Sliding = 9,
/// <summary>Performing a dash.</summary>
Dashing = 10,
/// <summary>Traversing an obstacle with a vault.</summary>
Vaulting = 11,
/// <summary>A state supplied by an add-on module rather than by Basic.</summary>
Custom = 12
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 84bc030051a24e06b3dfc5cb5cc2a0e7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Extensibility/LocomotionState.cs
uploadId: 997018
@@ -0,0 +1,47 @@
using System;
namespace CharacterMovement
{
/// <summary>
/// The individual locomotion abilities an external system can deny.
/// </summary>
/// <remarks>
/// Gameplay systems never edit the controller to restrict movement. They contribute an
/// <see cref="ICharacterMovementModifier"/> that blocks the capabilities they care about, and the
/// controller combines every contribution before acting on input.
/// </remarks>
[Flags]
public enum MovementCapability
{
None = 0,
/// <summary>Horizontal locomotion from player input.</summary>
Move = 1 << 0,
/// <summary>Raising the movement target to sprint speed.</summary>
Sprint = 1 << 1,
/// <summary>Starting a new jump, including buffered and coyote-time jumps.</summary>
Jump = 1 << 2,
/// <summary>Entering the crouch stance.</summary>
Crouch = 1 << 3,
/// <summary>Entering the prone stance.</summary>
Prone = 1 << 4,
/// <summary>Starting a slide.</summary>
Slide = 1 << 5,
/// <summary>Starting a dash.</summary>
Dash = 1 << 6,
/// <summary>Starting a vault over an obstacle.</summary>
Vault = 1 << 7,
/// <summary>Camera look input, for systems that own the view.</summary>
Look = 1 << 8,
All = Move | Sprint | Jump | Crouch | Prone | Slide | Dash | Vault | Look
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 62beafaa4cac4a7aa6844029a0d60887
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Extensibility/MovementCapability.cs
uploadId: 997018
@@ -0,0 +1,53 @@
using UnityEngine;
namespace CharacterMovement
{
/// <summary>
/// A ready-made <see cref="ICharacterMovementModifier"/> whose values you set directly.
/// </summary>
/// <remarks>
/// Use this when a system just needs to hold a restriction open for a while — a status effect, an
/// equipment weight penalty, a cutscene lock — and does not need to recompute anything per frame.
/// Get one from <see cref="PlayerController.CreateMovementModifier"/> and release it with
/// <see cref="PlayerController.RemoveMovementModifier"/>.
/// </remarks>
/// <example>
/// <code>
/// _heavyArmor = controller.CreateMovementModifier();
/// _heavyArmor.SpeedMultiplier = 0.75f;
/// _heavyArmor.BlockedCapabilities = MovementCapability.Sprint;
/// // later
/// controller.RemoveMovementModifier(_heavyArmor);
/// </code>
/// </example>
public sealed class MovementModifierHandle : ICharacterMovementModifier
{
private float _speedMultiplier = 1f;
/// <summary>Speed scale contributed by this handle. Clamped to zero or above.</summary>
public float SpeedMultiplier
{
get => _speedMultiplier;
set => _speedMultiplier = Mathf.Max(0f, value);
}
/// <summary>Capabilities this handle denies while it is registered.</summary>
public MovementCapability BlockedCapabilities { get; set; } = MovementCapability.None;
/// <summary>An optional label that shows up in the controller's debug overlay.</summary>
public string Label { get; set; }
/// <summary>Restores the handle to "no restrictions" without unregistering it.</summary>
public void Clear()
{
_speedMultiplier = 1f;
BlockedCapabilities = MovementCapability.None;
}
public void ApplyMovementModifiers(ref CharacterMovementModifiers modifiers)
{
modifiers.MultiplySpeed(_speedMultiplier);
modifiers.Block(BlockedCapabilities);
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: c9656d13b1a8484ba42c1098d025c638
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Extensibility/MovementModifierHandle.cs
uploadId: 997018
@@ -0,0 +1,12 @@
using UnityEngine;
namespace CharacterMovement
{
public interface IMovingPlatform
{
Transform PlatformTransform { get; }
Vector3 LinearVelocity { get; }
Vector3 AngularVelocity { get; }
Vector3 GetVelocityAtPoint(Vector3 worldPoint);
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 3dec05eee83f484d990d157f3899366e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/IMovingPlatform.cs
uploadId: 997018
@@ -0,0 +1,80 @@
using UnityEngine;
namespace CharacterMovement
{
[AddComponentMenu("Character Controller/Core/Moving Platform")]
public class MovingPlatform : MonoBehaviour, IMovingPlatform
{
[Tooltip("Rigidbody driving this platform, if it has one. Found on this GameObject if left empty.")]
[SerializeField] private Rigidbody platformRigidbody;
[Tooltip("Reads velocity from the Rigidbody when available. Turn off for platforms whose Rigidbody "
+ "velocity does not reflect their real motion, such as animated kinematic platforms.")]
[SerializeField] private bool preferRigidbodyVelocity = true;
private Vector3 _previousPosition;
private Quaternion _previousRotation;
private Vector3 _linearVelocity;
private Vector3 _angularVelocity;
public Transform PlatformTransform => transform;
public Vector3 LinearVelocity => ResolveLinearVelocity();
public Vector3 AngularVelocity => ResolveAngularVelocity();
private void Reset()
{
platformRigidbody = GetComponent<Rigidbody>();
}
private void OnEnable()
{
_previousPosition = transform.position;
_previousRotation = transform.rotation;
_linearVelocity = Vector3.zero;
_angularVelocity = Vector3.zero;
}
private void FixedUpdate()
{
float deltaTime = Mathf.Max(Time.fixedDeltaTime, 0.0001f);
Vector3 currentPosition = transform.position;
Quaternion currentRotation = transform.rotation;
_linearVelocity = (currentPosition - _previousPosition) / deltaTime;
Quaternion deltaRotation = currentRotation * Quaternion.Inverse(_previousRotation);
deltaRotation.ToAngleAxis(out float angle, out Vector3 axis);
if (angle > 180f)
angle -= 360f;
_angularVelocity = axis.sqrMagnitude > 0.0001f
? axis.normalized * (angle * Mathf.Deg2Rad / deltaTime)
: Vector3.zero;
_previousPosition = currentPosition;
_previousRotation = currentRotation;
}
public Vector3 GetVelocityAtPoint(Vector3 worldPoint)
{
if (preferRigidbodyVelocity && platformRigidbody)
return platformRigidbody.GetPointVelocity(worldPoint);
return LinearVelocity + Vector3.Cross(AngularVelocity, worldPoint - transform.position);
}
private Vector3 ResolveLinearVelocity()
{
if (preferRigidbodyVelocity && platformRigidbody)
return platformRigidbody.linearVelocity;
return _linearVelocity;
}
private Vector3 ResolveAngularVelocity()
{
if (preferRigidbodyVelocity && platformRigidbody)
return platformRigidbody.angularVelocity;
return _angularVelocity;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 0d0b7e5caf3c43a191f7afa2898dd665
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/MovingPlatform.cs
uploadId: 997018
@@ -0,0 +1,221 @@
using System;
using UnityEngine;
namespace CharacterMovement
{
public enum CharacterSpeedMode
{
Idle,
Walk,
Run,
Sprint,
Crouch,
Prone,
Slide,
Air,
Dash,
Vault,
Parkour
}
public interface ICharacterParkourState
{
}
public readonly struct CharacterControllerStateSnapshot
{
public CharacterControllerStateSnapshot(
string currentStateName,
Type currentStateType,
PlayerStance stance,
bool grounded,
Vector3 velocity,
Vector3 planarVelocity,
CharacterSpeedMode speedMode,
float slopeAngle,
bool hasSurfaceHit,
RaycastHit surfaceHit,
Transform platform)
{
CurrentStateName = currentStateName;
CurrentStateType = currentStateType;
Stance = stance;
Grounded = grounded;
Velocity = velocity;
PlanarVelocity = planarVelocity;
SpeedMode = speedMode;
SlopeAngle = slopeAngle;
HasSurfaceHit = hasSurfaceHit;
SurfaceHit = surfaceHit;
Platform = platform;
}
public string CurrentStateName { get; }
public Type CurrentStateType { get; }
public PlayerStance Stance { get; }
public bool Grounded { get; }
public Vector3 Velocity { get; }
public Vector3 PlanarVelocity { get; }
public CharacterSpeedMode SpeedMode { get; }
public float SlopeAngle { get; }
public bool HasSurfaceHit { get; }
public RaycastHit SurfaceHit { get; }
public Transform Platform { get; }
}
public partial class PlayerController
{
private bool _movementEnabled = true;
private bool _lookEnabled = true;
public bool IsMovementEnabled => _movementEnabled;
public bool IsLookEnabled => _lookEnabled;
public CharacterControllerStateSnapshot StateSnapshot => GetStateSnapshot();
public CharacterControllerStateSnapshot GetStateSnapshot()
{
State state = CurrentState;
bool grounded = IsGrounded();
Vector3 velocity = RigidBody ? RigidBody.linearVelocity : Vector3.zero;
Vector3 planarVelocity = Vector3.ProjectOnPlane(velocity, Vector3.up);
bool hasSurfaceHit = TryGetCurrentSurfaceHit(out RaycastHit surfaceHit);
float slopeAngle = hasSurfaceHit ? Vector3.Angle(surfaceHit.normal, Vector3.up) : 0f;
return new CharacterControllerStateSnapshot(
state?.GetType().Name ?? "None",
state?.GetType(),
CurrentStance,
grounded,
velocity,
planarVelocity,
ToSpeedMode(MovementState),
slopeAngle,
hasSurfaceHit,
surfaceHit,
CurrentPlatformTransform);
}
public void SetMovementEnabled(bool isEnabled)
{
_movementEnabled = isEnabled;
if (!isEnabled)
ClearBufferedInputs();
}
public void SetLookEnabled(bool isEnabled)
{
_lookEnabled = isEnabled;
}
/// <summary>
/// Applies an instant velocity change that locomotion will not immediately cancel.
/// </summary>
/// <remarks>
/// This is the entry point gameplay systems should use for knockback, explosions, recoil
/// pushback and launch pads. The impulse is tracked separately from locomotion velocity and
/// bleeds off at <see cref="ExternalForceDrag"/>, so the character keeps steering normally
/// while being pushed instead of having the push erased on the next physics step.
/// </remarks>
/// <example>
/// <code>
/// Vector3 away = (controller.transform.position - blastCentre).normalized;
/// controller.AddImpulse(away * 12f + Vector3.up * 4f);
/// </code>
/// </example>
public void AddImpulse(Vector3 velocityChange)
{
AddExternalForce(velocityChange);
}
/// <summary>
/// Adds a raw Rigidbody force. Prefer <see cref="AddImpulse"/> for gameplay pushes.
/// </summary>
/// <remarks>
/// Horizontal components are overwritten by locomotion on the next physics step, so this is
/// only appropriate for continuous physics such as wind or buoyancy applied every step, or
/// for purely vertical forces.
/// </remarks>
public void AddForce(Vector3 force, ForceMode forceMode = ForceMode.Force)
{
if (RigidBody)
RigidBody.AddForce(force, forceMode);
}
/// <summary>
/// Velocity currently being contributed by external systems, on top of locomotion.
/// </summary>
public Vector3 ExternalVelocity => _externalVelocity;
/// <summary>
/// Replaces the external velocity outright, rather than adding to it.
/// Use for effects that own the push completely, such as a conveyor or a wind volume.
/// </summary>
public void SetExternalVelocity(Vector3 velocity)
{
AddExternalForce(velocity, false);
}
/// <summary>Cancels any external velocity immediately.</summary>
public void ClearExternalVelocity()
{
AddExternalForce(Vector3.zero, false);
}
/// <summary>
/// Overwrites the rigidbody velocity directly, bypassing the external velocity system.
/// Locomotion will start correcting the horizontal part on the next physics step.
/// </summary>
public void SetVelocity(Vector3 velocity)
{
if (RigidBody)
RigidBody.linearVelocity = velocity;
}
public void Teleport(Vector3 position)
{
Teleport(position, RigidBody ? RigidBody.rotation : transform.rotation);
}
public void Teleport(Vector3 position, Quaternion rotation)
{
if (RigidBody)
{
RigidBody.position = position;
RigidBody.rotation = rotation;
RigidBody.linearVelocity = Vector3.zero;
RigidBody.angularVelocity = Vector3.zero;
}
else
{
transform.SetPositionAndRotation(position, rotation);
}
ResetPlatformTracking();
InvalidateGroundProbeCache();
}
public bool ForceStance(PlayerStance stance)
{
return TrySetStance(stance);
}
public bool TryStartSlide()
{
if (!CanStartSlide())
return false;
SwitchState(new PlayerSlideState(this));
return true;
}
public bool TryJump()
{
if (!CanStartJump())
return false;
SwitchState(new JumpingState(this));
return true;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 19e195918c2446179cc4e4002dcf2363
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.API.cs
uploadId: 997018
@@ -0,0 +1,233 @@
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private float _coyoteTimer;
private float _jumpBufferTimer;
private float _parkourBufferTimer;
private float _jumpGraceTimer;
private bool _jumpCutArmed;
public bool IsCoyoteTimeActive => _coyoteTimer > 0f;
public bool HasBufferedJumpIntent => _jumpBufferTimer > 0f;
public bool HasBufferedParkourIntent => _parkourBufferTimer > 0f;
/// <summary>
/// True for the few physics steps right after a jump launch. While it lasts the ground
/// stick, the ground snap and the coyote refresh stay off so the launch velocity survives
/// the frames where the capsule is still inside the ground probe range.
/// </summary>
public bool IsJumpGraceActive => _jumpGraceTimer > 0f;
public void NotifyMantleStarted() => MantleStarted?.Invoke();
public void NotifyMantleEnded() => MantleEnded?.Invoke();
public void NotifyExternalVaultStarted() => VaultStarted?.Invoke();
public void NotifyExternalVaultEnded() => VaultEnded?.Invoke();
public bool CanStartJump()
{
return CanMove
&& IsCapabilityAllowed(MovementCapability.Jump)
&& !IsJumpGraceActive
&& CurrentStance == PlayerStance.Standing
&& (IsGrounded() || IsCoyoteTimeActive);
}
/// <summary>
/// Applies the launch velocity. Returns false when the jump could not be started so
/// callers never leave the character in an airborne state that never left the ground.
/// </summary>
public bool Jump(float jumpForce)
{
if (!CanStartJump())
return false;
_coyoteTimer = 0f;
_jumpCutArmed = InputSource.IsJumpHeld;
_jumpGraceTimer = Mathf.Max(JumpGraceDuration, Time.fixedDeltaTime * 3f);
_groundStickSuppressionTimer = Mathf.Max(_groundStickSuppressionTimer, _jumpGraceTimer);
ClearBufferedInputs();
InvalidateGroundProbeCache();
Vector3 velocity = RigidBody.linearVelocity;
velocity.y = Mathf.Max(0f, jumpForce);
RigidBody.linearVelocity = velocity;
return true;
}
public void BufferJumpIntent()
{
_jumpBufferTimer = Mathf.Max(0f, JumpBufferTime);
}
public void BufferParkourIntent()
{
_parkourBufferTimer = Mathf.Max(0f, ParkourBufferTime);
}
public bool TryConsumeBufferedJumpIntent()
{
if (_jumpBufferTimer <= 0f)
return false;
_jumpBufferTimer = 0f;
return true;
}
public bool TryConsumeBufferedParkourIntent()
{
if (_parkourBufferTimer <= 0f)
return false;
_parkourBufferTimer = 0f;
return true;
}
public void ClearBufferedInputs()
{
_jumpBufferTimer = 0f;
_parkourBufferTimer = 0f;
}
public bool TryConsumeBufferedJump()
{
if (_jumpBufferTimer <= 0f)
return false;
if (_parkourBufferTimer > 0f && TryStartVault())
{
ClearBufferedInputs();
return true;
}
if (!CanStartJump())
return false;
ClearBufferedInputs();
SwitchState(new JumpingState(this));
return true;
}
private void TickBufferedInputs(float deltaTime)
{
if (_jumpBufferTimer > 0f)
_jumpBufferTimer -= deltaTime;
if (_parkourBufferTimer > 0f)
_parkourBufferTimer -= deltaTime;
}
/// <summary>
/// Trims the rest of the jump when the player lets go early, giving tap-versus-hold height
/// control. Only armed for jumps that actually started from a held button, so a scripted
/// <see cref="TryJump"/> or a buffered landing jump still reaches full height.
/// </summary>
private void ApplyVariableJumpHeight()
{
if (!_jumpCutArmed)
return;
float verticalVelocity = RigidBody.linearVelocity.y;
if (verticalVelocity <= 0f)
{
_jumpCutArmed = false;
return;
}
if (!VariableJumpHeight || InputSource.IsJumpHeld)
return;
_jumpCutArmed = false;
RigidBody.linearVelocity = new Vector3(
RigidBody.linearVelocity.x,
verticalVelocity * Mathf.Clamp01(JumpCutMultiplier),
RigidBody.linearVelocity.z);
}
/// <summary>
/// Adds extra downward acceleration while falling so descents feel weightier than ascents.
/// </summary>
private void ApplyFallGravity(float deltaTime)
{
if (FallGravityMultiplier <= 1f || !RigidBody || !RigidBody.useGravity)
return;
if (RigidBody.linearVelocity.y >= 0f)
return;
RigidBody.AddForce(
Physics.gravity * (GravityScale * (FallGravityMultiplier - 1f)),
ForceMode.Acceleration);
}
private void TickJumpGrace(float deltaTime)
{
if (_jumpGraceTimer > 0f)
_jumpGraceTimer = Mathf.Max(0f, _jumpGraceTimer - deltaTime);
}
private void UpdateCoyoteTimer(float deltaTime)
{
if (_groundProbingEnabled)
{
bool isGrounded = IsGrounded();
_debugLastIsGrounded = isGrounded;
if (isGrounded && !IsJumpGraceActive)
_coyoteTimer = CoyoteTime;
else
_coyoteTimer -= deltaTime;
return;
}
_debugLastIsGrounded = false;
_debugHasSurfaceHit = false;
_debugSupplementaryRayCount = 0;
_coyoteTimer = 0f;
}
private void OnJumpBuffered()
{
BufferJumpIntent();
BufferParkourIntent();
}
private void OnMovementStateChanged(State previousState, State nextState)
{
_fallingEventLatched = nextState is FallingState;
if (nextState is JumpingState)
JumpStarted?.Invoke();
if (IsAirborneMovementState(previousState) && nextState is IGroundLocomotionState)
Landed?.Invoke();
bool wasSliding = IsSlideState(previousState);
bool isSliding = IsSlideState(nextState);
if (!wasSliding && isSliding)
SlideStarted?.Invoke();
else if (wasSliding && !isSliding)
SlideEnded?.Invoke();
bool wasVaulting = previousState is VaultingState;
bool isVaulting = nextState is VaultingState;
if (!wasVaulting && isVaulting)
VaultStarted?.Invoke();
else if (wasVaulting && !isVaulting)
VaultEnded?.Invoke();
}
private static bool IsAirborneMovementState(State state)
{
return state is JumpingState || state is FallingState;
}
private static bool IsSlideState(State state)
{
return state is PlayerSlideState || state is SlidingState;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 13ffab5701a7418baf8ec36ad4ab45f5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Actions.cs
uploadId: 997018
@@ -0,0 +1,54 @@
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
[Header("Camera")]
[SerializeField]
[Tooltip("Transform movement input is interpreted relative to, so pressing forward moves "
+ "away from the camera. Leave empty to use the main camera.")]
private Transform mainCameraTransform;
[SerializeField]
[Tooltip("Re-finds the main camera at runtime if it is missing or destroyed, which keeps "
+ "movement correct when the camera is spawned or swapped at play time.")]
private bool autoFindMainCamera = true;
[SerializeField, Min(0f)]
[Tooltip("How often to re-check for the main camera, in seconds, while none is assigned.")]
private float mainCameraRefreshInterval = 0.25f;
[SerializeField]
[Tooltip("Locks and hides the hardware cursor when the character starts. Turn this off if "
+ "your game manages the cursor itself or shows menus over gameplay.")]
private bool lockCursorOnStart = true;
public void SetMainCameraTransform(Transform cameraTransform)
{
if (cameraTransform)
{
mainCameraTransform = cameraTransform;
MainCameraTransform = cameraTransform;
}
}
private void RefreshMainCameraReference(bool force = false)
{
if (MainCameraTransform && MainCameraTransform != transform)
return;
if (!autoFindMainCamera)
return;
if (!force && mainCameraRefreshInterval > 0f && Time.unscaledTime < _nextMainCameraRefreshTime)
return;
_nextMainCameraRefreshTime = Time.unscaledTime + mainCameraRefreshInterval;
Camera mainCamera = SceneReferenceResolver.FindMainCameraInSameScene(this);
if (mainCamera)
SetMainCameraTransform(mainCamera.transform);
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 921c30e93a0a4b6785e4036ce27d9b1b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Camera.cs
uploadId: 997018
@@ -0,0 +1,276 @@
using System.Text;
using UnityEngine;
#if CC_TMP_AVAILABLE
using TMPro;
#endif
namespace CharacterMovement
{
public partial class PlayerController
{
[Header("Debug")]
#if CC_TMP_AVAILABLE
[Tooltip("Optional TextMeshPro label that shows the current state name at runtime.")]
[SerializeField] private TextMeshProUGUI _stateLabel;
#endif
[Header("Debug Tools")]
[Tooltip("Master switch for the debug overlay and all scene gizmos. Turn off for release builds; "
+ "the debug code then costs nothing.")]
[SerializeField] private bool _enableDebugTools = true;
[Tooltip("Draws the on-screen state readout during play.")]
[SerializeField] private bool _showDebugOverlay = true;
[Tooltip("Keeps drawing gizmos when the character is not selected in the hierarchy. Useful while "
+ "tuning, noisy in a busy scene.")]
[SerializeField] private bool _drawGizmosWhenNotSelected;
[Tooltip("Draws the ground sweep and supplementary rays, coloured by whether they found walkable "
+ "ground.")]
[SerializeField] private bool _drawGroundProbeGizmos = true;
[Tooltip("Draws the step-up probes and the resolved step height.")]
[SerializeField] private bool _drawStepUpGizmos = true;
[Tooltip("Draws the current rigidbody velocity as an arrow.")]
[SerializeField] private bool _drawVelocityGizmos = true;
[Tooltip("Draws the requested movement direction as an arrow.")]
[SerializeField] private bool _drawMovementGizmos = true;
[Tooltip("Draws the normal of the surface under the character.")]
[SerializeField] private bool _drawSurfaceNormalGizmos = true;
[Tooltip("Length multiplier for the velocity and movement arrows.")]
[SerializeField, Min(0.05f)] private float _debugVectorScale = 0.35f;
[Tooltip("Colour for probes that found walkable ground.")]
[SerializeField] private Color _groundHitColor = new Color(0.2f, 1f, 0.3f, 1f);
[Tooltip("Colour for probes that found nothing, or found an unwalkable surface.")]
[SerializeField] private Color _groundMissColor = new Color(1f, 0.3f, 0.3f, 1f);
[Tooltip("Colour for the step-up probe gizmos.")]
[SerializeField] private Color _stepUpColor = new Color(1f, 0.72f, 0.2f, 1f);
[Tooltip("Colour for the velocity arrow.")]
[SerializeField] private Color _velocityColor = new Color(0.95f, 0.15f, 1f, 1f);
[Tooltip("Colour for the movement direction arrow.")]
[SerializeField] private Color _movementColor = new Color(0.2f, 0.8f, 1f, 1f);
private enum StepUpDebugResult
{
NotAttempted,
NoMoveInput,
NotGrounded,
NoPlanarDirection,
NoFootObstacle,
ObstacleAboveStep,
NoStepSurface,
UnwalkableLanding,
InvalidStepHeight,
Stepped
}
private bool _debugLastIsGrounded;
private bool _debugHasSurfaceHit;
private RaycastHit _debugSurfaceHit;
private float _debugLastSlopeAngle;
private Vector3 _debugLastMoveDirection;
private Vector3 _debugLastAppliedVelocity;
private Vector3 _debugCapsuleTop;
private Vector3 _debugCapsuleBottom;
private float _debugCapsuleCastRadius;
private float _debugCapsuleCastDistance;
private readonly Vector3[] _debugSupplementaryRayOrigins = new Vector3[8];
private readonly Vector3[] _debugSupplementaryRayDirections = new Vector3[8];
private readonly float[] _debugSupplementaryRayDistances = new float[8];
private readonly bool[] _debugSupplementaryRayHits = new bool[8];
private readonly RaycastHit[] _debugSupplementaryRayHitInfos = new RaycastHit[8];
private int _debugSupplementaryRayCount;
private StepUpDebugResult _debugStepUpResult;
private float _debugStepHeight;
private float _debugStepCheckDistance;
private float _debugStepMaxHeight;
private Vector3 _debugStepDirection;
private Vector3 _debugStepOrigin;
private Vector3 _debugStepAboveOrigin;
private Vector3 _debugStepProbeOrigin;
private bool _debugStepFootBlocked;
private bool _debugStepHeadBlocked;
private bool _debugStepProbeHit;
private bool _debugStepLandingWalkable;
private RaycastHit _debugStepHit;
private string _debugPreviousStateName = "None";
private string _debugCurrentStateName = "None";
private float _debugLastStateChangeTime;
private readonly StringBuilder _debugOverlayBuilder = new StringBuilder(512);
private GUIStyle _debugOverlayStyle;
public void SetStateLabel(string label)
{
#if CC_TMP_AVAILABLE
if (_stateLabel) _stateLabel.SetText(label);
#endif
}
public void SetDebugOverlayVisible(bool visible) => _showDebugOverlay = visible;
public string GetDebugSummary()
{
_debugOverlayBuilder.Clear();
BuildDebugOverlayText(_debugOverlayBuilder);
return _debugOverlayBuilder.ToString();
}
private void OnStateChangedDebug(State previous, State next)
{
_debugPreviousStateName = previous?.GetType().Name ?? "None";
_debugCurrentStateName = next?.GetType().Name ?? "None";
_debugLastStateChangeTime = Time.time;
}
private void OnGUI()
{
if (!_enableDebugTools || !_showDebugOverlay || !Application.isPlaying) return;
EnsureDebugOverlayStyle();
_debugOverlayBuilder.Clear();
BuildDebugOverlayText(_debugOverlayBuilder);
GUI.Box(new Rect(10f, 10f, 460f, 240f), _debugOverlayBuilder.ToString(), _debugOverlayStyle);
}
private void EnsureDebugOverlayStyle()
{
if (_debugOverlayStyle != null) return;
_debugOverlayStyle = new GUIStyle(GUI.skin.box)
{
alignment = TextAnchor.UpperLeft,
fontSize = 12,
richText = false,
wordWrap = false,
padding = new RectOffset(8, 8, 8, 8)
};
}
private void BuildDebugOverlayText(StringBuilder builder)
{
builder.AppendLine("Character Controller Debug");
builder.Append("State: ").Append(_debugCurrentStateName)
.Append(" (prev: ").Append(_debugPreviousStateName).AppendLine(")");
builder.Append("Last Transition: ").Append(Time.time - _debugLastStateChangeTime).AppendLine("s ago");
builder.Append("Grounded: ").Append(_debugLastIsGrounded)
.Append(" | Coyote: ").Append(IsCoyoteTimeActive)
.Append(" | Slope: ").Append(_debugLastSlopeAngle.ToString("F1")).AppendLine(" deg");
builder.Append("Velocity: ").Append(RigidBody ? RigidBody.linearVelocity.ToString("F3") : "n/a").AppendLine();
builder.Append("Applied Vel: ").Append(_debugLastAppliedVelocity.ToString("F3")).AppendLine();
builder.Append("Move Dir: ").Append(_debugLastMoveDirection.ToString("F3")).AppendLine();
builder.Append("StepUp: ").Append(_debugStepUpResult)
.Append(" | Height: ").Append(_debugStepHeight.ToString("F3")).AppendLine("m");
builder.Append("Step Flags: foot=")
.Append(_debugStepFootBlocked)
.Append(", headBlocked=")
.Append(_debugStepHeadBlocked)
.Append(", probeHit=")
.Append(_debugStepProbeHit)
.Append(", walkable=")
.Append(_debugStepLandingWalkable);
}
private void OnDrawGizmos()
{
if (_drawGizmosWhenNotSelected)
DrawDebugGizmos();
}
private void OnDrawGizmosSelected()
{
if (!_drawGizmosWhenNotSelected)
DrawDebugGizmos();
}
private void DrawDebugGizmos()
{
if (!_enableDebugTools || !Application.isPlaying) return;
if (_drawGroundProbeGizmos && _groundProbingEnabled)
{
Vector3 castDirection = Vector3.down;
Gizmos.color = _debugHasSurfaceHit ? _groundHitColor : _groundMissColor;
Gizmos.DrawWireSphere(_debugCapsuleTop, _debugCapsuleCastRadius);
Gizmos.DrawWireSphere(_debugCapsuleBottom, _debugCapsuleCastRadius);
Gizmos.DrawLine(_debugCapsuleTop, _debugCapsuleBottom);
Gizmos.DrawWireSphere(_debugCapsuleTop + castDirection * _debugCapsuleCastDistance, _debugCapsuleCastRadius);
Gizmos.DrawWireSphere(_debugCapsuleBottom + castDirection * _debugCapsuleCastDistance, _debugCapsuleCastRadius);
Gizmos.DrawLine(_debugCapsuleTop, _debugCapsuleTop + castDirection * _debugCapsuleCastDistance);
Gizmos.DrawLine(_debugCapsuleBottom, _debugCapsuleBottom + castDirection * _debugCapsuleCastDistance);
for (int i = 0; i < _debugSupplementaryRayCount && i < _debugSupplementaryRayOrigins.Length; i++)
{
Vector3 origin = _debugSupplementaryRayOrigins[i];
Vector3 end = origin + _debugSupplementaryRayDirections[i] * _debugSupplementaryRayDistances[i];
Gizmos.color = _debugSupplementaryRayHits[i] ? _groundHitColor : _groundMissColor;
Gizmos.DrawLine(origin, end);
if (_debugSupplementaryRayHits[i])
{
Gizmos.DrawSphere(_debugSupplementaryRayHitInfos[i].point, 0.02f);
if (_drawSurfaceNormalGizmos)
{
Gizmos.DrawLine(
_debugSupplementaryRayHitInfos[i].point,
_debugSupplementaryRayHitInfos[i].point + _debugSupplementaryRayHitInfos[i].normal * 0.25f
);
}
}
}
if (_debugHasSurfaceHit)
{
Gizmos.color = _groundHitColor;
Gizmos.DrawSphere(_debugSurfaceHit.point, 0.03f);
if (_drawSurfaceNormalGizmos)
{
Gizmos.DrawLine(_debugSurfaceHit.point, _debugSurfaceHit.point + _debugSurfaceHit.normal * 0.35f);
}
}
}
if (_drawStepUpGizmos)
{
Gizmos.color = _stepUpColor;
if (_debugStepDirection.sqrMagnitude > 0.0001f && _debugStepCheckDistance > 0.001f)
{
Gizmos.DrawLine(_debugStepOrigin, _debugStepOrigin + _debugStepDirection * _debugStepCheckDistance);
Gizmos.DrawLine(_debugStepAboveOrigin, _debugStepAboveOrigin + _debugStepDirection * _debugStepCheckDistance);
}
float probeDistance = Mathf.Max(0.05f, _debugStepMaxHeight + 0.05f);
Gizmos.DrawLine(_debugStepProbeOrigin, _debugStepProbeOrigin + Vector3.down * probeDistance);
if (_debugStepProbeHit)
{
Gizmos.DrawSphere(_debugStepHit.point, 0.03f);
if (_drawSurfaceNormalGizmos)
Gizmos.DrawLine(_debugStepHit.point, _debugStepHit.point + _debugStepHit.normal * 0.3f);
}
}
if (_drawVelocityGizmos && RigidBody)
DrawVectorGizmo(transform.position, RigidBody.linearVelocity * _debugVectorScale, _velocityColor);
if (_drawMovementGizmos)
{
DrawVectorGizmo(
transform.position + Vector3.up * 0.05f,
_debugLastMoveDirection * (Mathf.Max(1f, Speed) * _debugVectorScale),
_movementColor
);
}
}
private static void DrawVectorGizmo(Vector3 origin, Vector3 vector, Color color)
{
if (vector.sqrMagnitude < 0.0001f) return;
Gizmos.color = color;
Vector3 end = origin + vector;
Gizmos.DrawLine(origin, end);
Vector3 back = -vector.normalized * 0.15f;
Vector3 right = Vector3.Cross(vector.normalized, Vector3.up);
if (right.sqrMagnitude < 0.0001f)
right = Vector3.Cross(vector.normalized, Vector3.right);
right.Normalize();
Gizmos.DrawLine(end, end + back + right * 0.06f);
Gizmos.DrawLine(end, end + back - right * 0.06f);
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 7e48d6cd519a4f6499db5f3f3d26b4da
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Debug.cs
uploadId: 997018
@@ -0,0 +1,154 @@
using System.Collections.Generic;
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private readonly List<ICharacterMovementModifier> _movementModifiers = new List<ICharacterMovementModifier>(4);
private CharacterMovementModifiers _activeModifiers = CharacterMovementModifiers.Unrestricted;
/// <summary>
/// The combined speed scale from <see cref="SpeedMultiplier"/> and every registered modifier.
/// This is what locomotion actually uses.
/// </summary>
public float EffectiveSpeedMultiplier => Mathf.Max(0f, SpeedMultiplier) * _activeModifiers.SpeedMultiplier;
/// <summary>Every capability currently denied by at least one registered modifier.</summary>
public MovementCapability BlockedCapabilities => _activeModifiers.BlockedCapabilities;
/// <summary>How many modifiers are currently registered. Useful for debug overlays and tests.</summary>
public int MovementModifierCount => _movementModifiers.Count;
/// <summary>True when nothing is blocking horizontal locomotion.</summary>
public bool CanMove => _movementEnabled && IsCapabilityAllowed(MovementCapability.Move);
/// <summary>True when the character is allowed to raise its speed target to sprint speed.</summary>
public bool CanSprint => CanMove && IsCapabilityAllowed(MovementCapability.Sprint);
/// <summary>True when camera look is allowed.</summary>
public bool CanLook => _lookEnabled && IsCapabilityAllowed(MovementCapability.Look);
/// <summary>
/// True when the sprint input is held and sprinting is currently permitted.
/// Locomotion states use this rather than reading the raw input, so a gameplay system that
/// blocks <see cref="MovementCapability.Sprint"/> takes effect everywhere at once.
/// </summary>
public bool IsSprintRequested => CanSprint && IsSprintInputActive;
/// <summary>True when the walk modifier is held and walking is possible.</summary>
public bool IsWalkRequested => CanMove && InputSource.IsWalking;
/// <summary>
/// True when a dash may start: movement is allowed, dashing is not blocked, and the
/// cooldown has elapsed.
/// </summary>
public bool CanStartDash()
{
return CanMove
&& IsCapabilityAllowed(MovementCapability.Dash)
&& DashCooldown <= 0f;
}
/// <summary>
/// Registers a modifier. Safe to call more than once with the same instance; it is only added
/// once. Modifiers combine multiplicatively for speed and by union for blocked capabilities,
/// so registration order does not affect the result.
/// </summary>
public void AddMovementModifier(ICharacterMovementModifier modifier)
{
if (modifier == null || _movementModifiers.Contains(modifier))
return;
_movementModifiers.Add(modifier);
EvaluateMovementModifiers();
}
/// <summary>Unregisters a modifier. Its restrictions stop applying immediately.</summary>
public void RemoveMovementModifier(ICharacterMovementModifier modifier)
{
if (modifier == null || !_movementModifiers.Remove(modifier))
return;
EvaluateMovementModifiers();
}
/// <summary>
/// Creates and registers a <see cref="MovementModifierHandle"/> for the common case where a
/// system only needs to hold a restriction open. Release it with
/// <see cref="RemoveMovementModifier"/>.
/// </summary>
public MovementModifierHandle CreateMovementModifier(string label = null)
{
MovementModifierHandle handle = new MovementModifierHandle { Label = label };
AddMovementModifier(handle);
return handle;
}
/// <summary>Removes every registered modifier. Mainly useful when pooling characters.</summary>
public void ClearMovementModifiers()
{
if (_movementModifiers.Count == 0)
return;
_movementModifiers.Clear();
EvaluateMovementModifiers();
}
/// <summary>True when every capability in <paramref name="capability"/> is currently allowed.</summary>
public bool IsCapabilityAllowed(MovementCapability capability)
{
return _activeModifiers.IsAllowed(capability);
}
/// <summary>
/// Abilities switched off in the inspector, expressed as capability flags.
/// </summary>
/// <remarks>
/// Design-time toggles and runtime modifiers go through the same gate, so a system asking
/// "can this character sprint?" gets one answer whether sprinting was disabled on the
/// prefab or denied by a status effect this frame.
/// </remarks>
public MovementCapability DisabledAbilities
{
get
{
MovementCapability disabled = MovementCapability.None;
if (!AllowSprint) disabled |= MovementCapability.Sprint;
if (!AllowJump) disabled |= MovementCapability.Jump;
if (!AllowCrouch) disabled |= MovementCapability.Crouch;
if (!AllowProne) disabled |= MovementCapability.Prone;
if (!AllowDash) disabled |= MovementCapability.Dash;
if (!AllowSlide) disabled |= MovementCapability.Slide;
if (!AllowVault) disabled |= MovementCapability.Vault;
return disabled;
}
}
/// <summary>
/// Recombines every registered modifier. Called automatically before states run each update
/// and each physics step, so it rarely needs to be called by hand.
/// </summary>
public void EvaluateMovementModifiers()
{
CharacterMovementModifiers combined = CharacterMovementModifiers.Unrestricted;
combined.Block(DisabledAbilities);
// Walk backwards so a modifier whose component was destroyed can be dropped in the same
// pass. Leaving it registered would freeze the character at whatever it last asked for.
for (int i = _movementModifiers.Count - 1; i >= 0; i--)
{
ICharacterMovementModifier modifier = _movementModifiers[i];
if (modifier == null || (modifier is Object unityModifier && !unityModifier))
{
_movementModifiers.RemoveAt(i);
continue;
}
modifier.ApplyMovementModifiers(ref combined);
}
_activeModifiers = combined;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 7822253f5f8f4a4d936b7760838bef22
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Extensions.cs
uploadId: 997018
@@ -0,0 +1,545 @@
using System.Collections.Generic;
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private readonly CharacterGroundProbe _groundProbe = new CharacterGroundProbe();
private GroundProbeDebugData _groundProbeDebugData = new GroundProbeDebugData(GroundProbeDebugData.MaxSupplementaryRays);
private Vector3 _platformVelocity;
private Transform _currentPlatformTransform;
private IMovingPlatform _currentMovingPlatform;
private Vector3 _platformLocalPoint;
private Vector3 _lastPlatformWorldPoint;
private Quaternion _lastPlatformRotation;
private bool _hasPlatformTracking;
private float _groundStickSuppressionTimer;
private readonly List<MonoBehaviour> _platformComponentBuffer = new List<MonoBehaviour>(4);
// Keyed on the physics step, not the render frame: when physics runs more often than
// rendering, a frame-keyed cache hands later steps a stale grounded result.
private int _physicsStep;
private int _lastGroundProbeStep = -1;
private bool _cachedIsGrounded;
private bool _cachedHasSurfaceHit;
private RaycastHit _cachedGroundHit;
private int _lastExtendedProbeStep = -1;
private bool _cachedHasExtendedHit;
private RaycastHit _cachedExtendedHit;
private bool _slopeAlignmentEnabled = true;
private bool _groundProbingEnabled = true;
private LayerMask SurfaceProbeMask => GroundLayerMask | StairsLayerMask;
public bool IsSlopeAlignmentEnabled => _slopeAlignmentEnabled;
public bool IsGroundProbingEnabled => _groundProbingEnabled;
public Transform CurrentPlatformTransform => _currentPlatformTransform;
public IMovingPlatform CurrentMovingPlatform => _currentMovingPlatform;
public bool CanApplyGroundStick => _groundStickSuppressionTimer <= 0f;
/// <summary>
/// False while the character has just been lifted deliberately (a step up, a jump launch).
/// Snapping back to the surface during that window would undo the lift before the forward
/// motion has carried the capsule over the obstacle.
/// </summary>
public bool CanSnapToGround => CanApplyGroundStick && !IsJumpGraceActive;
public void SetSlopeAlignmentEnabled(bool isEnabled)
{
_slopeAlignmentEnabled = isEnabled;
}
public void SetGroundProbingEnabled(bool isEnabled)
{
_groundProbingEnabled = isEnabled;
if (isEnabled)
return;
_platformVelocity = Vector3.zero;
ResetPlatformTracking();
_debugLastIsGrounded = false;
_debugHasSurfaceHit = false;
_debugSupplementaryRayCount = 0;
_coyoteTimer = 0f;
InvalidateGroundProbeCache();
}
/// <summary>
/// True when a ground locomotion state should hand over to the airborne state: nothing is
/// supporting the character and either coyote time has lapsed or something is pushing it up.
/// </summary>
public bool ShouldEnterAirborneState =>
_groundProbingEnabled
&& !IsGrounded()
&& (!IsCoyoteTimeActive || VerticalVelocity > AirborneLaunchVelocityThreshold);
public bool IsGrounded()
{
TryGetCachedGroundProbe(out _, out bool isGrounded);
return isGrounded;
}
/// <summary>
/// Runs the ground probe at most once per physics step and reports both whether anything was
/// hit and whether that surface is walkable.
/// </summary>
private bool TryGetCachedGroundProbe(out RaycastHit surfaceHit, out bool isGrounded)
{
if (!_groundProbingEnabled)
{
_debugLastIsGrounded = false;
_debugHasSurfaceHit = false;
_debugSupplementaryRayCount = 0;
surfaceHit = default;
isGrounded = false;
return false;
}
if (_lastGroundProbeStep == _physicsStep)
{
surfaceHit = _cachedGroundHit;
isGrounded = _cachedIsGrounded;
return _cachedHasSurfaceHit;
}
_lastGroundProbeStep = _physicsStep;
if (!TryGetSurfaceHit(out RaycastHit hitInfo))
{
_debugLastIsGrounded = false;
_cachedIsGrounded = false;
_cachedHasSurfaceHit = false;
_cachedGroundHit = default;
surfaceHit = default;
isGrounded = false;
return false;
}
_debugHasSurfaceHit = true;
_debugSurfaceHit = hitInfo;
_debugLastSlopeAngle = Vector3.Angle(hitInfo.normal, Vector3.up);
bool walkable = IsSurfaceWalkable(hitInfo);
_debugLastIsGrounded = walkable;
_cachedGroundHit = hitInfo;
_cachedHasSurfaceHit = true;
_cachedIsGrounded = walkable;
surfaceHit = hitInfo;
isGrounded = walkable;
return true;
}
/// <summary>
/// The extended probe, reaching a further <see cref="GroundSnapDistance"/> below the feet.
/// Shared by slope queries, step support, ground snapping and platform tracking so those
/// four do not each pay for their own sweep.
/// </summary>
private bool TryGetCachedExtendedProbe(out RaycastHit surfaceHit)
{
if (!_groundProbingEnabled)
{
surfaceHit = default;
return false;
}
if (_lastExtendedProbeStep == _physicsStep)
{
surfaceHit = _cachedExtendedHit;
return _cachedHasExtendedHit;
}
_lastExtendedProbeStep = _physicsStep;
_cachedHasExtendedHit = TryGetSurfaceHit(out _cachedExtendedHit, GroundSnapDistance);
surfaceHit = _cachedExtendedHit;
return _cachedHasExtendedHit;
}
/// <summary>
/// Opens a new physics step, so the cached probes are recomputed once and then reused by
/// every system that asks during that step.
/// </summary>
private void BeginGroundProbeStep()
{
_physicsStep++;
}
public void AlignToSurface(float deltaTime)
{
if (!TryGetCachedGroundProbe(out RaycastHit hit, out bool isGrounded) || !isGrounded)
return;
Vector3 groundNormal = hit.normal;
if (Vector3.Angle(groundNormal, Vector3.up) < 1f)
groundNormal = Vector3.up;
Vector3 projectedForward = Vector3.ProjectOnPlane(transform.forward, groundNormal);
if (projectedForward.sqrMagnitude < 0.0001f)
projectedForward = Vector3.ProjectOnPlane(transform.right, groundNormal);
if (projectedForward.sqrMagnitude < 0.0001f) return;
Quaternion targetRotation = Quaternion.LookRotation(projectedForward.normalized, groundNormal);
RigidBody.MoveRotation(Quaternion.Slerp(RigidBody.rotation, targetRotation, Alignment * deltaTime));
}
public RaycastHit? OnSlope()
{
if (!_groundProbingEnabled)
return null;
if (TryGetGroundHit(out RaycastHit slopeHit))
return slopeHit;
if (TryGetCachedExtendedProbe(out slopeHit))
return slopeHit;
return null;
}
public float GetSlopeAdjustedAdditionalSpeed(Vector3 movement, RaycastHit slopeHit, float additionalSpeed)
{
float baseTargetSpeed = Mathf.Max(0f, Speed + additionalSpeed);
float multiplier = GetSlopeSpeedMultiplier(movement, slopeHit.normal);
return baseTargetSpeed * multiplier - Speed;
}
public void SlideDownSlope(Vector3 slopeNormal)
{
if (slopeNormal.sqrMagnitude < 0.0001f) return;
Vector3 slideDirection = Vector3.ProjectOnPlane(Vector3.down, slopeNormal).normalized;
if (slideDirection.sqrMagnitude < 0.0001f) return;
RigidBody.AddForce(slideDirection * SlideForce, ForceMode.Acceleration);
}
public void StepUp(Vector3 moveDir)
{
float maxStepHeight = StepHeight;
_debugStepMaxHeight = maxStepHeight;
_debugStepHeight = 0f;
_debugStepDirection = Vector3.zero;
_debugStepFootBlocked = false;
_debugStepHeadBlocked = false;
_debugStepProbeHit = false;
_debugStepLandingWalkable = false;
_debugStepUpResult = StepUpDebugResult.NotAttempted;
if (!_groundProbingEnabled)
return;
if (moveDir.sqrMagnitude < 0.0001f)
{
_debugStepUpResult = StepUpDebugResult.NoMoveInput;
return;
}
bool hasSurfaceSupport = TryGetCachedExtendedProbe(out RaycastHit supportHit)
&& IsSurfaceWalkable(supportHit);
bool hasGroundSupport = IsGrounded() || IsCoyoteTimeActive || hasSurfaceSupport;
if (!hasGroundSupport)
{
_debugStepUpResult = StepUpDebugResult.NotGrounded;
return;
}
Vector3 dir = Vector3.ProjectOnPlane(moveDir, Vector3.up).normalized;
_debugStepDirection = dir;
if (dir.sqrMagnitude < 0.0001f)
{
_debugStepUpResult = StepUpDebugResult.NoPlanarDirection;
return;
}
LayerMask probeMask = SurfaceProbeMask;
Vector3 capsuleCenter = transform.TransformPoint(CapsuleCollider.center);
float footY = capsuleCenter.y - CapsuleCollider.height * 0.5f;
if (hasSurfaceSupport)
footY = Mathf.Max(footY, supportHit.point.y);
float checkDist = CapsuleCollider.radius + StepCheckDistance;
_debugStepCheckDistance = checkDist;
Vector3 origin = new Vector3(capsuleCenter.x, footY + 0.05f, capsuleCenter.z);
_debugStepOrigin = origin;
float probeRadius = Mathf.Max(0.02f, CapsuleCollider.radius * StepProbeRadiusScale);
_debugStepFootBlocked = Physics.SphereCast(origin, probeRadius, dir, out _, checkDist, probeMask, QueryTriggerInteraction.Ignore);
if (!_debugStepFootBlocked)
{
_debugStepUpResult = StepUpDebugResult.NoFootObstacle;
return;
}
Vector3 aboveOrigin = new Vector3(capsuleCenter.x, footY + maxStepHeight + probeRadius + 0.02f, capsuleCenter.z);
_debugStepAboveOrigin = aboveOrigin;
_debugStepHeadBlocked = Physics.SphereCast(aboveOrigin, probeRadius, dir, out _, checkDist, probeMask, QueryTriggerInteraction.Ignore);
if (_debugStepHeadBlocked)
{
_debugStepUpResult = StepUpDebugResult.ObstacleAboveStep;
return;
}
Vector3 probe = aboveOrigin + dir * checkDist;
_debugStepProbeOrigin = probe;
_debugStepProbeHit = Physics.Raycast(probe, Vector3.down, out RaycastHit hit, maxStepHeight + probeRadius + 0.05f, probeMask, QueryTriggerInteraction.Ignore);
if (!_debugStepProbeHit)
{
_debugStepUpResult = StepUpDebugResult.NoStepSurface;
return;
}
_debugStepHit = hit;
_debugStepLandingWalkable = IsSurfaceWalkable(hit);
if (!_debugStepLandingWalkable)
{
_debugStepUpResult = StepUpDebugResult.UnwalkableLanding;
return;
}
float stepHeight = hit.point.y - footY;
_debugStepHeight = stepHeight;
if (stepHeight <= 0.01f || stepHeight > maxStepHeight)
{
_debugStepUpResult = StepUpDebugResult.InvalidStepHeight;
return;
}
_coyoteTimer = CoyoteTime;
_groundStickSuppressionTimer = Mathf.Max(
_groundStickSuppressionTimer,
Mathf.Max(Time.fixedDeltaTime * 2f, JumpGraceDuration));
RigidBody.MovePosition(RigidBody.position + Vector3.up * (stepHeight + 0.01f));
if (RigidBody.linearVelocity.y < 0f)
RigidBody.linearVelocity = new Vector3(RigidBody.linearVelocity.x, 0f, RigidBody.linearVelocity.z);
InvalidateGroundProbeCache();
_debugStepUpResult = StepUpDebugResult.Stepped;
}
public bool TryGetCurrentSurfaceHit(out RaycastHit surfaceHit)
{
if (TryGetGroundHit(out surfaceHit))
return true;
return TryGetCachedExtendedProbe(out surfaceHit);
}
private void UpdatePlatformMotion(float deltaTime)
{
if (!TryGetCachedGroundProbe(out RaycastHit hit, out _))
{
ResetPlatformTracking();
return;
}
IMovingPlatform movingPlatform = ResolveMovingPlatform(hit.collider);
Transform platformTransform = movingPlatform?.PlatformTransform
? movingPlatform.PlatformTransform
: hit.rigidbody ? hit.rigidbody.transform : null;
if (!platformTransform)
{
ResetPlatformTracking();
return;
}
Vector3 sampledVelocity = movingPlatform != null
? movingPlatform.GetVelocityAtPoint(hit.point)
: hit.rigidbody.GetPointVelocity(hit.point);
if (_hasPlatformTracking && _currentPlatformTransform == platformTransform)
{
Vector3 currentWorldPoint = platformTransform.TransformPoint(_platformLocalPoint);
Vector3 transformVelocity = (currentWorldPoint - _lastPlatformWorldPoint) / Mathf.Max(deltaTime, 0.0001f);
if (transformVelocity.sqrMagnitude > 0.000001f)
sampledVelocity = transformVelocity;
Quaternion deltaRotation = platformTransform.rotation * Quaternion.Inverse(_lastPlatformRotation);
if (deltaRotation != Quaternion.identity && RigidBody)
RigidBody.MoveRotation(deltaRotation * RigidBody.rotation);
}
_currentPlatformTransform = platformTransform;
_currentMovingPlatform = movingPlatform;
_platformVelocity = sampledVelocity;
_platformLocalPoint = platformTransform.InverseTransformPoint(RigidBody.position);
_lastPlatformWorldPoint = platformTransform.TransformPoint(_platformLocalPoint);
_lastPlatformRotation = platformTransform.rotation;
_hasPlatformTracking = true;
}
private void UpdateGroundStickSuppression(float deltaTime)
{
if (_groundStickSuppressionTimer > 0f)
_groundStickSuppressionTimer = Mathf.Max(0f, _groundStickSuppressionTimer - deltaTime);
}
private IMovingPlatform ResolveMovingPlatform(Collider hitCollider)
{
if (!hitCollider)
return null;
MovingPlatform movingPlatform = hitCollider.GetComponentInParent<MovingPlatform>();
if (movingPlatform)
return movingPlatform;
_platformComponentBuffer.Clear();
hitCollider.GetComponentsInParent(false, _platformComponentBuffer);
for (int i = 0; i < _platformComponentBuffer.Count; i++)
{
if (_platformComponentBuffer[i] is IMovingPlatform customPlatform)
{
_platformComponentBuffer.Clear();
return customPlatform;
}
}
_platformComponentBuffer.Clear();
return null;
}
private void ResetPlatformTracking()
{
_platformVelocity = Vector3.zero;
_currentPlatformTransform = null;
_currentMovingPlatform = null;
_platformLocalPoint = Vector3.zero;
_lastPlatformWorldPoint = Vector3.zero;
_lastPlatformRotation = Quaternion.identity;
_hasPlatformTracking = false;
}
private bool TryGetSurfaceHit(out RaycastHit bestHit, float extraDistance = 0f)
{
bool hasHit = _groundProbe.TryGetSurfaceHit(
transform,
CapsuleCollider,
SurfaceProbeMask,
GroundProbeRadiusScale,
GroundCheckDistance,
extraDistance,
GroundProbeEpsilon,
GroundProbeLiftOffset,
UseSupplementaryGroundRays,
SupplementaryRaySpread,
out bestHit,
ref _groundProbeDebugData);
SyncGroundProbeDebugData();
return hasHit;
}
private bool IsSurfaceWalkable(RaycastHit hit)
{
if (!hit.collider) return false;
int surfaceLayer = hit.collider.gameObject.layer;
int surfaceLayerMask = 1 << surfaceLayer;
bool isGround = (GroundLayerMask.value & surfaceLayerMask) != 0;
bool isStairs = !isGround && (StairsLayerMask.value & surfaceLayerMask) != 0;
float maxAngle = isStairs ? MaxStairsAngle : MaxSlopeAngle;
return hit.normal.y >= Mathf.Cos(maxAngle * Mathf.Deg2Rad);
}
private bool TryGetGroundHit(out RaycastHit groundHit)
{
TryGetCachedGroundProbe(out groundHit, out bool isGrounded);
return isGrounded;
}
/// <summary>
/// Forces the next query to re-probe. Used after the controller moves the body itself, since
/// the cached result describes where the character was before the move.
/// </summary>
private void InvalidateGroundProbeCache()
{
_lastGroundProbeStep = -1;
_lastExtendedProbeStep = -1;
}
private float GetSlopeSpeedMultiplier(Vector3 movement, Vector3 surfaceNormal)
{
Vector3 planarMovement = Vector3.ProjectOnPlane(movement, Vector3.up);
if (planarMovement.sqrMagnitude <= 0.0001f)
return 1f;
Vector3 downhill = Vector3.ProjectOnPlane(Vector3.down, surfaceNormal);
if (downhill.sqrMagnitude <= 0.0001f)
return 1f;
float slopeDot = Vector3.Dot(planarMovement.normalized, downhill.normalized);
if (slopeDot > 0.1f)
return Mathf.Lerp(1f, DownhillSlopeSpeedMultiplier, slopeDot);
if (slopeDot < -0.1f)
return Mathf.Lerp(1f, UphillSlopeSpeedMultiplier, -slopeDot);
return 1f;
}
private bool TrySnapToGround()
{
if (GroundSnapDistance <= 0f || RigidBody.linearVelocity.y > 0f || !CanSnapToGround)
return false;
if (!TryGetCachedExtendedProbe(out RaycastHit hit) || !IsSurfaceWalkable(hit))
return false;
float snapDistance = Mathf.Clamp(hit.distance, 0f, GroundSnapDistance);
if (snapDistance <= 0.001f)
return false;
Vector3 velocity = RigidBody.linearVelocity;
if (velocity.y < 0f)
{
velocity.y = 0f;
RigidBody.linearVelocity = velocity;
}
RigidBody.MovePosition(RigidBody.position + Vector3.down * snapDistance);
_coyoteTimer = CoyoteTime;
_cachedGroundHit = hit;
_cachedHasSurfaceHit = true;
_cachedIsGrounded = true;
_lastGroundProbeStep = _physicsStep;
return true;
}
private void HandleCeilingCollision()
{
if (CeilingCheckDistance <= 0f || RigidBody.linearVelocity.y <= 0f)
return;
float radius = Mathf.Max(0.01f, CapsuleCollider.radius * CeilingProbeRadiusScale);
float halfHeight = Mathf.Max(CapsuleCollider.height * 0.5f, radius);
float segment = Mathf.Max(0f, halfHeight - radius);
Vector3 center = transform.TransformPoint(CapsuleCollider.center);
Vector3 top = center + transform.up * segment;
if (!Physics.SphereCast(top, radius, Vector3.up, out RaycastHit hit, CeilingCheckDistance, SurfaceProbeMask, QueryTriggerInteraction.Ignore)
|| IsSelfCollider(hit.collider))
{
return;
}
Vector3 velocity = RigidBody.linearVelocity;
velocity.y = 0f;
RigidBody.linearVelocity = velocity;
}
private void SyncGroundProbeDebugData()
{
_debugHasSurfaceHit = _groundProbeDebugData.HasSurfaceHit;
_debugSurfaceHit = _groundProbeDebugData.SurfaceHit;
_debugLastSlopeAngle = _groundProbeDebugData.SlopeAngle;
_debugCapsuleTop = _groundProbeDebugData.CapsuleTop;
_debugCapsuleBottom = _groundProbeDebugData.CapsuleBottom;
_debugCapsuleCastRadius = _groundProbeDebugData.CapsuleCastRadius;
_debugCapsuleCastDistance = _groundProbeDebugData.CapsuleCastDistance;
_debugSupplementaryRayCount = _groundProbeDebugData.SupplementaryRayCount;
for (int i = 0; i < _debugSupplementaryRayOrigins.Length; i++)
{
_debugSupplementaryRayOrigins[i] = _groundProbeDebugData.SupplementaryRayOrigins[i];
_debugSupplementaryRayDirections[i] = _groundProbeDebugData.SupplementaryRayDirections[i];
_debugSupplementaryRayDistances[i] = _groundProbeDebugData.SupplementaryRayDistances[i];
_debugSupplementaryRayHits[i] = _groundProbeDebugData.SupplementaryRayHits[i];
_debugSupplementaryRayHitInfos[i] = _groundProbeDebugData.SupplementaryRayHitInfos[i];
}
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: b61edcf3ca0c4edb8e41d4801ee7ebf7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Grounding.cs
uploadId: 997018
@@ -0,0 +1,141 @@
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
[SerializeField]
[Tooltip("Optional. A component implementing ICharacterInputSource that replaces the default "
+ "InputHandler. Leave empty to use the InputHandler on this character.")]
private MonoBehaviour inputSourceBehaviour;
private ICharacterInputSource _inputSource;
private bool _sprintToggleActive;
private bool _sprintInputWasDown;
/// <summary>
/// Where the controller reads player intent from. Never null once the controller has started;
/// falls back to an empty source so locomotion cannot throw when input is missing.
/// </summary>
public ICharacterInputSource InputSource => _inputSource ?? EmptyCharacterInputSource.Instance;
/// <summary>
/// Swaps the input source at runtime — for AI possession, cutscenes, replays or a network
/// stream. Pass null to fall back to the serialized source or the local
/// <see cref="InputHandler"/>.
/// </summary>
public void SetInputSource(ICharacterInputSource source)
{
if (ReferenceEquals(_inputSource, source))
return;
UnsubscribeFromInputSource();
_inputSource = source ?? ResolveSerializedInputSource();
SubscribeToInputSource();
}
/// <summary>
/// The sprint input after the configured activation mode is applied, before permissions.
/// </summary>
public bool IsSprintInputActive =>
SprintActivation == SprintActivationMode.Toggle ? _sprintToggleActive : InputSource.IsSprinting;
/// <summary>
/// Turns the raw sprint input into a held state. In toggle mode a press flips sprinting on
/// or off, and releasing the movement stick ends it, which is what players expect from a
/// toggle rather than sprinting again the next time they move.
/// </summary>
private void UpdateSprintActivation()
{
bool sprintInputDown = InputSource.IsSprinting;
if (SprintActivation == SprintActivationMode.Toggle)
{
if (sprintInputDown && !_sprintInputWasDown)
_sprintToggleActive = !_sprintToggleActive;
if (!InputSource.IsMoving || !CanSprint)
_sprintToggleActive = false;
}
else
{
_sprintToggleActive = false;
}
_sprintInputWasDown = sprintInputDown;
}
private void InitializeInputSource()
{
_inputSource = ResolveSerializedInputSource();
SubscribeToInputSource();
}
private ICharacterInputSource ResolveSerializedInputSource()
{
if (inputSourceBehaviour is ICharacterInputSource explicitSource)
return explicitSource;
if (inputSourceBehaviour)
{
Debug.LogWarning(
$"[PlayerController] '{inputSourceBehaviour.GetType().Name}' on '{name}' does not implement "
+ $"{nameof(ICharacterInputSource)} and will be ignored.",
this);
}
if (!InputHandler)
InputHandler = GetComponent<InputHandler>() ?? gameObject.AddComponent<InputHandler>();
return InputHandler;
}
private void SubscribeToInputSource()
{
if (_inputSource == null)
return;
_inputSource.JumpPerformed += OnJumpBuffered;
_inputSource.CrouchPerformed += OnCrouch;
_inputSource.PronePerformed += OnProne;
}
private void UnsubscribeFromInputSource()
{
if (_inputSource == null)
return;
_inputSource.JumpPerformed -= OnJumpBuffered;
_inputSource.CrouchPerformed -= OnCrouch;
_inputSource.PronePerformed -= OnProne;
}
}
/// <summary>
/// A neutral input source used when none is configured, so states can read input without
/// null checks and a misconfigured character simply stands still instead of throwing.
/// </summary>
internal sealed class EmptyCharacterInputSource : ICharacterInputSource
{
public static readonly EmptyCharacterInputSource Instance = new EmptyCharacterInputSource();
private EmptyCharacterInputSource()
{
}
public Vector2 MoveDirection => Vector2.zero;
public bool IsMoving => false;
public bool IsSprinting => false;
public bool IsWalking => false;
public bool IsCrouching => false;
public bool IsProne => false;
public bool IsJumpHeld => false;
#pragma warning disable 67 // Never raised by design: this source produces no input.
public event System.Action JumpPerformed;
public event System.Action DashPerformed;
public event System.Action CrouchPerformed;
public event System.Action PronePerformed;
#pragma warning restore 67
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: d190b1c94efa4ce799c48dbc247e475d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Input.cs
uploadId: 997018
@@ -0,0 +1,74 @@
using System.Collections.Generic;
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private readonly List<SkillModule> _skillModules = new List<SkillModule>();
private bool _isReady;
public void RegisterModule(SkillModule module)
{
if (module == null || _skillModules.Contains(module))
return;
_skillModules.Add(module);
if (_isReady)
module.Initialize(this);
}
public void UnregisterModule(SkillModule module)
{
if (module == null || !_skillModules.Remove(module))
return;
if (_isReady)
module.Cleanup();
}
private void InitializeSkillModules()
{
foreach (SkillModule module in GetComponents<SkillModule>())
{
if (!_skillModules.Contains(module))
_skillModules.Add(module);
}
_isReady = true;
foreach (SkillModule module in _skillModules)
module.Initialize(this);
}
private void UpdateSkillModules(float deltaTime)
{
for (int i = 0; i < _skillModules.Count; i++)
{
SkillModule module = _skillModules[i];
if (module) module.UpdateModule(deltaTime);
}
}
private void FixedUpdateSkillModules(float deltaTime)
{
for (int i = 0; i < _skillModules.Count; i++)
{
SkillModule module = _skillModules[i];
if (module) module.FixedUpdateModule(deltaTime);
}
}
private void CleanupSkillModules()
{
for (int i = _skillModules.Count - 1; i >= 0; i--)
{
SkillModule module = _skillModules[i];
if (module) module.Cleanup();
}
_skillModules.Clear();
_isReady = false;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 74bb64e874954109b7fb8081c5acc2bf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Modules.cs
uploadId: 997018
@@ -0,0 +1,229 @@
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private Vector3 _externalVelocity;
private bool _movementFacingEnabled = true;
public bool IsMovementFacingEnabled => _movementFacingEnabled;
public override void Move(Vector3 moveDirection, float deltaTime, float additionalSpeed = 0)
{
if (!CanMove)
{
moveDirection = Vector3.zero;
additionalSpeed = 0f;
}
moveDirection = Vector3.ClampMagnitude(moveDirection, 1f);
_debugLastMoveDirection = moveDirection;
float targetSpeed = Mathf.Max(0f, (Speed + additionalSpeed) * EffectiveSpeedMultiplier);
Vector3 targetLocomotionVelocity = moveDirection * targetSpeed;
Vector3 currentVelocity = RigidBody.linearVelocity;
Vector3 currentPlanarVelocity = Vector3.ProjectOnPlane(currentVelocity, Vector3.up);
Vector3 additivePlanarVelocity = new Vector3(
_platformVelocity.x + _externalVelocity.x,
0f,
_platformVelocity.z + _externalVelocity.z);
Vector3 currentLocomotionPlanarVelocity = currentPlanarVelocity - additivePlanarVelocity;
Vector3 targetPlanarVelocity = Vector3.ProjectOnPlane(targetLocomotionVelocity, Vector3.up);
bool isJumpOrFallState = CurrentState is JumpingState || CurrentState is FallingState;
Vector3 planarDirection = Vector3.ProjectOnPlane(moveDirection, Vector3.up);
bool hasMoveInput = planarDirection.sqrMagnitude > 0.0001f;
bool isGrounded = IsGrounded();
bool useAirControl = isJumpOrFallState || !isGrounded;
float acceleration = useAirControl
? (hasMoveInput ? AirAcceleration : AirDeceleration)
: (hasMoveInput ? GroundAcceleration : GroundDeceleration);
Vector3 locomotionPlanarVelocity = targetPlanarVelocity;
if (acceleration > 0f)
{
locomotionPlanarVelocity = Vector3.MoveTowards(
currentLocomotionPlanarVelocity,
targetPlanarVelocity,
acceleration * deltaTime);
}
Vector3 targetVelocity = locomotionPlanarVelocity + additivePlanarVelocity;
targetVelocity.y = ResolveVerticalVelocity(
moveDirection,
planarDirection,
locomotionPlanarVelocity,
currentVelocity.y,
isGrounded,
isJumpOrFallState);
targetVelocity.y += _externalVelocity.y;
if (_platformVelocity.y > 0f)
targetVelocity.y = Mathf.Max(targetVelocity.y, _platformVelocity.y);
_debugLastAppliedVelocity = targetVelocity;
RigidBody.linearVelocity = targetVelocity;
}
/// <summary>
/// Ground locomotion on a slope is fed a direction that already follows the surface, so the
/// vertical part of that direction has to be rebuilt from the planar speed actually reached.
/// Without it the character is pinned to a flat plane while climbing or descending.
/// </summary>
private float ResolveVerticalVelocity(
Vector3 moveDirection,
Vector3 planarDirection,
Vector3 locomotionPlanarVelocity,
float currentVerticalVelocity,
bool isGrounded,
bool isJumpOrFallState)
{
float planarDirectionMagnitude = planarDirection.magnitude;
bool followsSurface = isGrounded
&& !isJumpOrFallState
&& planarDirectionMagnitude > 0.0001f
&& Mathf.Abs(moveDirection.y) > 0.0001f;
if (followsSurface)
{
float slopeRatio = moveDirection.y / planarDirectionMagnitude;
return locomotionPlanarVelocity.magnitude * slopeRatio;
}
if (isGrounded && !isJumpOrFallState)
return Mathf.Min(0f, currentVerticalVelocity);
return currentVerticalVelocity;
}
/// <summary>
/// The ground speed the current input and stance ask for. Airborne states use it as their
/// target so a jump neither accelerates a walking character nor drains sprint momentum.
/// </summary>
public float GetInputTargetSpeed()
{
if (!CanMove)
return Speed;
switch (CurrentStance)
{
case PlayerStance.Prone:
return ProneSpeed;
case PlayerStance.Crouching:
return CrouchSpeed;
}
if (IsSprintRequested)
return SprintSpeed;
if (IsWalkRequested)
return WalkSpeed;
return Speed;
}
/// <summary>
/// Extra speed an airborne state should request so it keeps the momentum it took off with
/// while still allowing air control up to the speed the current input asks for.
/// </summary>
public float GetAirborneAdditionalSpeed()
{
return Mathf.Max(GetInputTargetSpeed(), GetPlanarSpeed()) - Speed;
}
public float GetPlanarSpeed()
{
return Vector3.ProjectOnPlane(RigidBody.linearVelocity, Vector3.up).magnitude;
}
public Vector3 CalculateMovement()
{
if (!CanMove)
return Vector3.zero;
Vector2 moveInput = InputSource.MoveDirection;
if (moveInput.sqrMagnitude <= 0.0001f)
return Vector3.zero;
Transform reference = MainCameraTransform ? MainCameraTransform : transform;
Vector3 forward = Vector3.ProjectOnPlane(reference.forward, Vector3.up);
if (forward.sqrMagnitude <= 0.0001f)
forward = Vector3.ProjectOnPlane(transform.forward, Vector3.up);
if (forward.sqrMagnitude <= 0.0001f)
forward = Vector3.forward;
forward.Normalize();
Vector3 right = Vector3.Cross(Vector3.up, forward);
if (right.sqrMagnitude <= 0.0001f)
right = Vector3.right;
else
right.Normalize();
return forward * moveInput.y + right * moveInput.x;
}
public void AddExternalForce(Vector3 force, bool add = true)
{
if (add)
_externalVelocity += force;
else
_externalVelocity = force;
}
public void SetMovementFacingEnabled(bool isEnabled)
{
_movementFacingEnabled = isEnabled;
}
public bool CanStartSlide()
{
if (!CanMove || !IsCapabilityAllowed(MovementCapability.Slide))
return false;
if (SlideCooldown > 0f || CurrentStance != PlayerStance.Standing)
return false;
if (!IsGrounded() || !InputSource.IsMoving || !IsSprintRequested)
return false;
Vector3 planarVelocity = Vector3.ProjectOnPlane(RigidBody.linearVelocity, Vector3.up);
return planarVelocity.magnitude >= MinimumSlideInputSpeed || CalculateMovement().sqrMagnitude > 0.0001f;
}
public void BeginSlide()
{
TryStartSlide();
}
public void SwitchToBaseGroundLocomotion()
{
if (CurrentStance == PlayerStance.Prone)
{
if (!(CurrentState is ProneState))
SwitchState(new ProneState(this));
return;
}
if (CurrentStance == PlayerStance.Crouching)
{
if (!(CurrentState is CrouchingState))
SwitchState(new CrouchingState(this));
return;
}
if (CanMove && InputSource.IsMoving)
{
if (!(CurrentState is MovingState))
SwitchState(new MovingState(this));
return;
}
if (!(CurrentState is IdleState))
SwitchState(new IdleState(this));
}
private void DecayExternalVelocity(float deltaTime)
{
_externalVelocity = Vector3.MoveTowards(_externalVelocity, Vector3.zero, ExternalForceDrag * deltaTime);
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: cee50ff874644381a4a34d6a711395b6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Movement.cs
uploadId: 997018
@@ -0,0 +1,225 @@
using System;
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
[SerializeField, Min(0f)]
[Tooltip("Planar speed above which the character counts as moving, for StartedMoving / "
+ "StoppedMoving. Raise it if idle physics jitter triggers footsteps.")]
private float movementEventSpeedThreshold = 0.15f;
/// <summary>
/// Planar speed above which the character counts as moving for
/// <see cref="StartedMoving"/> and <see cref="StoppedMoving"/>.
/// </summary>
public float MovementEventSpeedThreshold
{
get => movementEventSpeedThreshold;
private set => movementEventSpeedThreshold = value;
}
private LocomotionState _movementState = LocomotionState.None;
private bool _wasGrounded;
private bool _wasMoving;
private bool _wasSprinting;
private bool _wasCrouching;
private bool _hasObservedFirstFrame;
/// <summary>
/// The current locomotion state as a stable enum. Prefer this over inspecting
/// <see cref="StateController.CurrentState"/>, whose concrete types are internal detail.
/// </summary>
public LocomotionState MovementState => _movementState;
/// <summary>Full rigidbody velocity in world space.</summary>
public Vector3 CurrentVelocity => RigidBody ? RigidBody.linearVelocity : Vector3.zero;
/// <summary>Horizontal velocity with the vertical component removed.</summary>
public Vector3 PlanarVelocity => Vector3.ProjectOnPlane(CurrentVelocity, Vector3.up);
/// <summary>Vertical velocity. Negative while falling.</summary>
public float VerticalVelocity => RigidBody ? RigidBody.linearVelocity.y : 0f;
/// <summary>
/// Normal of the surface under the character, or <see cref="Vector3.up"/> when airborne.
/// </summary>
public Vector3 GroundNormal =>
TryGetCurrentSurfaceHit(out RaycastHit hit) ? hit.normal : Vector3.up;
/// <summary>Angle in degrees between the supporting surface and world up. Zero when airborne.</summary>
public float GroundAngle =>
TryGetCurrentSurfaceHit(out RaycastHit hit) ? Vector3.Angle(hit.normal, Vector3.up) : 0f;
/// <summary>True when the supporting surface is within the configured slope limits.</summary>
public bool IsOnWalkableGround =>
TryGetCurrentSurfaceHit(out RaycastHit hit) && IsSurfaceWalkable(hit);
/// <summary>True while the character is in an airborne locomotion state.</summary>
public bool IsAirborne =>
_movementState == LocomotionState.Jumping || _movementState == LocomotionState.Falling;
/// <summary>Raised when the locomotion state changes, with the previous and new state.</summary>
public event Action<LocomotionState, LocomotionState> MovementStateChanged;
/// <summary>Raised when the character regains ground contact.</summary>
public event Action Grounded;
/// <summary>Raised when the character loses ground contact, by jumping or walking off an edge.</summary>
public event Action LeftGround;
/// <summary>Raised when planar speed rises above the movement threshold.</summary>
public event Action StartedMoving;
/// <summary>Raised when planar speed drops below the movement threshold.</summary>
public event Action StoppedMoving;
/// <summary>Raised when sprinting begins. Does not fire while sprint is blocked by a modifier.</summary>
public event Action SprintStarted;
/// <summary>Raised when sprinting ends.</summary>
public event Action SprintEnded;
/// <summary>Raised when the character enters the crouch stance.</summary>
public event Action CrouchStarted;
/// <summary>Raised when the character leaves the crouch stance.</summary>
public event Action CrouchEnded;
/// <summary>
/// Recomputes the observable state and raises any edge events. Runs once per frame from the
/// controller's update; exposed so tests and tooling can force a refresh.
/// </summary>
public void RefreshObservableState()
{
LocomotionState nextState = ResolveLocomotionState();
if (nextState != _movementState)
{
LocomotionState previousState = _movementState;
_movementState = nextState;
MovementStateChanged?.Invoke(previousState, nextState);
}
bool isGrounded = _groundProbingEnabled && IsGrounded();
bool isMoving = PlanarVelocity.sqrMagnitude
> movementEventSpeedThreshold * movementEventSpeedThreshold;
bool isSprinting = IsSprintRequested && isMoving;
bool isCrouching = CurrentStance == PlayerStance.Crouching;
// The first frame establishes a baseline instead of reporting every state as a change.
if (!_hasObservedFirstFrame)
{
_hasObservedFirstFrame = true;
_wasGrounded = isGrounded;
_wasMoving = isMoving;
_wasSprinting = isSprinting;
_wasCrouching = isCrouching;
return;
}
if (isGrounded != _wasGrounded)
{
_wasGrounded = isGrounded;
if (isGrounded)
Grounded?.Invoke();
else
LeftGround?.Invoke();
}
if (isMoving != _wasMoving)
{
_wasMoving = isMoving;
if (isMoving)
StartedMoving?.Invoke();
else
StoppedMoving?.Invoke();
}
if (isSprinting != _wasSprinting)
{
_wasSprinting = isSprinting;
if (isSprinting)
SprintStarted?.Invoke();
else
SprintEnded?.Invoke();
}
if (isCrouching != _wasCrouching)
{
_wasCrouching = isCrouching;
if (isCrouching)
CrouchStarted?.Invoke();
else
CrouchEnded?.Invoke();
}
}
/// <summary>
/// The single place locomotion state is derived from. The animation and speed-mode enums are
/// projections of this, so all three can never disagree.
/// </summary>
private LocomotionState ResolveLocomotionState()
{
State state = CurrentState;
if (state == null)
return LocomotionState.None;
if (state is VaultingState) return LocomotionState.Vaulting;
if (state is DashingState) return LocomotionState.Dashing;
if (state is PlayerSlideState || state is SlidingState) return LocomotionState.Sliding;
if (state is JumpingState) return LocomotionState.Jumping;
if (state is FallingState) return LocomotionState.Falling;
if (state is ICharacterParkourState) return LocomotionState.Custom;
if (CurrentStance == PlayerStance.Prone) return LocomotionState.Prone;
if (CurrentStance == PlayerStance.Crouching) return LocomotionState.Crouching;
if (!CanMove || !InputSource.IsMoving) return LocomotionState.Idle;
if (IsSprintRequested) return LocomotionState.Sprinting;
if (IsWalkRequested) return LocomotionState.Walking;
return LocomotionState.Running;
}
/// <summary>Projects a locomotion state onto the coarser speed-mode enum.</summary>
public static CharacterSpeedMode ToSpeedMode(LocomotionState state)
{
switch (state)
{
case LocomotionState.Walking: return CharacterSpeedMode.Walk;
case LocomotionState.Running: return CharacterSpeedMode.Run;
case LocomotionState.Sprinting: return CharacterSpeedMode.Sprint;
case LocomotionState.Crouching: return CharacterSpeedMode.Crouch;
case LocomotionState.Prone: return CharacterSpeedMode.Prone;
case LocomotionState.Jumping:
case LocomotionState.Falling: return CharacterSpeedMode.Air;
case LocomotionState.Sliding: return CharacterSpeedMode.Slide;
case LocomotionState.Dashing: return CharacterSpeedMode.Dash;
case LocomotionState.Vaulting: return CharacterSpeedMode.Vault;
case LocomotionState.Custom: return CharacterSpeedMode.Parkour;
default: return CharacterSpeedMode.Idle;
}
}
/// <summary>Projects a locomotion state onto the animator's state enum.</summary>
public static CharacterAnimationState ToAnimationState(LocomotionState state)
{
switch (state)
{
case LocomotionState.Idle: return CharacterAnimationState.Idle;
case LocomotionState.Walking:
case LocomotionState.Running:
case LocomotionState.Sprinting: return CharacterAnimationState.Moving;
case LocomotionState.Crouching: return CharacterAnimationState.Crouching;
case LocomotionState.Prone: return CharacterAnimationState.Prone;
case LocomotionState.Jumping: return CharacterAnimationState.Jumping;
case LocomotionState.Falling: return CharacterAnimationState.Falling;
case LocomotionState.Sliding: return CharacterAnimationState.Sliding;
case LocomotionState.Dashing: return CharacterAnimationState.Dashing;
case LocomotionState.Vaulting: return CharacterAnimationState.Vaulting;
case LocomotionState.Custom: return CharacterAnimationState.Parkour;
default: return CharacterAnimationState.None;
}
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 0b77e05c1f574d4a8d689b382a420e12
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Observability.cs
uploadId: 997018
@@ -0,0 +1,140 @@
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private void ApplyMotorSettings()
{
if (!MotorSettings)
return;
Speed = MotorSettings.RunSpeed;
SprintSpeed = MotorSettings.SprintSpeed;
WalkSpeed = MotorSettings.WalkSpeed;
CrouchSpeed = MotorSettings.CrouchSpeed;
ProneSpeed = MotorSettings.ProneSpeed;
GroundAcceleration = MotorSettings.GroundAcceleration;
GroundDeceleration = MotorSettings.GroundDeceleration;
AirAcceleration = MotorSettings.AirAcceleration;
AirDeceleration = MotorSettings.AirDeceleration;
JumpingForce = MotorSettings.JumpingForce;
VariableJumpHeight = MotorSettings.VariableJumpHeight;
JumpCutMultiplier = MotorSettings.JumpCutMultiplier;
FallGravityMultiplier = MotorSettings.FallGravityMultiplier;
CanMoveWhileJumping = MotorSettings.CanMoveWhileJumping;
CoyoteTime = MotorSettings.CoyoteTime;
JumpBufferTime = MotorSettings.JumpBufferTime;
ParkourBufferTime = MotorSettings.ParkourBufferTime;
GravityScale = MotorSettings.GravityScale;
MaxFallSpeed = MotorSettings.MaxFallSpeed;
JumpGraceDuration = MotorSettings.JumpGraceDuration;
CrouchCapsuleHeight = MotorSettings.CrouchCapsuleHeight;
ProneCapsuleHeight = MotorSettings.ProneCapsuleHeight;
StanceTransitionSpeed = MotorSettings.StanceTransitionSpeed;
SlideDuration = MotorSettings.SlideDuration;
SlideStartSpeed = MotorSettings.SlideStartSpeed;
SlideEndSpeed = MotorSettings.SlideEndSpeed;
SlideSteeringStrength = MotorSettings.SlideSteeringStrength;
SlideCooldownDuration = MotorSettings.SlideCooldownDuration;
MinimumSlideInputSpeed = MotorSettings.MinimumSlideInputSpeed;
MaxSlopeSlideSpeed = MotorSettings.MaxSlopeSlideSpeed;
MaxSlopeAngle = MotorSettings.MaxSlopeAngle;
MaxStairsAngle = MotorSettings.MaxStairsAngle;
GroundProbeRadiusScale = MotorSettings.GroundProbeRadiusScale;
GroundCheckDistance = MotorSettings.GroundCheckDistance;
GroundSnapDistance = MotorSettings.GroundSnapDistance;
GroundStickForce = MotorSettings.GroundStickForce;
StepHeight = MotorSettings.StepHeight;
StepCheckDistance = MotorSettings.StepCheckDistance;
StepProbeRadiusScale = MotorSettings.StepProbeRadiusScale;
CeilingCheckDistance = MotorSettings.CeilingCheckDistance;
CeilingProbeRadiusScale = MotorSettings.CeilingProbeRadiusScale;
StanceClearanceRadiusScale = MotorSettings.StanceClearanceRadiusScale;
UseSupplementaryGroundRays = MotorSettings.UseSupplementaryGroundRays;
SupplementaryRaySpread = MotorSettings.SupplementaryRaySpread;
GroundProbeLiftOffset = MotorSettings.GroundProbeLiftOffset;
GroundProbeEpsilon = MotorSettings.GroundProbeEpsilon;
UphillSlopeSpeedMultiplier = MotorSettings.UphillSlopeSpeedMultiplier;
DownhillSlopeSpeedMultiplier = MotorSettings.DownhillSlopeSpeedMultiplier;
SlideForce = MotorSettings.SlideForce;
Alignment = MotorSettings.SlopeAlignment;
AlignToSlopeNormal = MotorSettings.AlignToSlopeNormal;
ExternalForceDrag = MotorSettings.ExternalForceDrag;
AirborneLaunchVelocityThreshold = MotorSettings.AirborneLaunchVelocityThreshold;
FallDetectionVelocityThreshold = MotorSettings.FallDetectionVelocityThreshold;
}
private void ValidateMotorValues()
{
Speed = Mathf.Max(0f, Speed);
SprintSpeed = Mathf.Max(0f, SprintSpeed);
WalkSpeed = Mathf.Max(0f, WalkSpeed);
CrouchSpeed = Mathf.Max(0f, CrouchSpeed);
ProneSpeed = Mathf.Max(0f, ProneSpeed);
GroundAcceleration = Mathf.Max(0f, GroundAcceleration);
GroundDeceleration = Mathf.Max(0f, GroundDeceleration);
AirAcceleration = Mathf.Max(0f, AirAcceleration);
AirDeceleration = Mathf.Max(0f, AirDeceleration);
JumpingForce = Mathf.Max(0f, JumpingForce);
JumpCutMultiplier = Mathf.Clamp(JumpCutMultiplier, 0.05f, 1f);
FallGravityMultiplier = Mathf.Max(1f, FallGravityMultiplier);
MovementEventSpeedThreshold = Mathf.Max(0f, MovementEventSpeedThreshold);
CoyoteTime = Mathf.Max(0f, CoyoteTime);
JumpBufferTime = Mathf.Max(0f, JumpBufferTime);
ParkourBufferTime = Mathf.Max(0f, ParkourBufferTime);
GravityScale = Mathf.Max(0.01f, GravityScale);
MaxFallSpeed = Mathf.Max(0f, MaxFallSpeed);
DashDuration = Mathf.Max(0f, DashDuration);
DashLength = Mathf.Max(0f, DashLength);
DashCooldownDuration = Mathf.Max(0f, DashCooldownDuration);
CrouchCapsuleHeight = Mathf.Max(0.1f, CrouchCapsuleHeight);
ProneCapsuleHeight = Mathf.Max(0.1f, ProneCapsuleHeight);
StanceTransitionSpeed = Mathf.Max(0f, StanceTransitionSpeed);
SlideDuration = Mathf.Max(0.05f, SlideDuration);
SlideStartSpeed = Mathf.Max(0f, SlideStartSpeed);
SlideEndSpeed = Mathf.Max(0f, SlideEndSpeed);
SlideSteeringStrength = Mathf.Max(0f, SlideSteeringStrength);
SlideCooldownDuration = Mathf.Max(0f, SlideCooldownDuration);
MinimumSlideInputSpeed = Mathf.Max(0f, MinimumSlideInputSpeed);
GroundCheckDistance = Mathf.Max(0.01f, GroundCheckDistance);
GroundSnapDistance = Mathf.Max(0f, GroundSnapDistance);
GroundStickForce = Mathf.Max(0f, GroundStickForce);
StepHeight = Mathf.Max(0.01f, StepHeight);
StepCheckDistance = Mathf.Max(0.01f, StepCheckDistance);
CeilingCheckDistance = Mathf.Max(0f, CeilingCheckDistance);
SlideForce = Mathf.Max(0f, SlideForce);
Alignment = Mathf.Max(0f, Alignment);
ExternalForceDrag = Mathf.Max(0f, ExternalForceDrag);
JumpGraceDuration = Mathf.Max(0f, JumpGraceDuration);
MaxSlopeSlideSpeed = Mathf.Max(0f, MaxSlopeSlideSpeed);
GroundProbeLiftOffset = Mathf.Max(0f, GroundProbeLiftOffset);
GroundProbeEpsilon = Mathf.Max(0f, GroundProbeEpsilon);
AirborneLaunchVelocityThreshold = Mathf.Max(0f, AirborneLaunchVelocityThreshold);
FallDetectionVelocityThreshold = Mathf.Max(0f, FallDetectionVelocityThreshold);
VaultGroundOffset = Mathf.Max(0f, VaultGroundOffset);
AirDashDownwardBoost = Mathf.Max(0f, AirDashDownwardBoost);
}
private void ApplyGravityScale(float deltaTime)
{
if (Mathf.Approximately(GravityScale, 1f) || !RigidBody || !RigidBody.useGravity)
return;
RigidBody.AddForce(Physics.gravity * (GravityScale - 1f), ForceMode.Acceleration);
}
private void ClampFallSpeed()
{
if (MaxFallSpeed <= 0f || !RigidBody)
return;
Vector3 velocity = RigidBody.linearVelocity;
if (velocity.y >= -MaxFallSpeed)
return;
velocity.y = -MaxFallSpeed;
RigidBody.linearVelocity = velocity;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 91bf0fc3e40b4ab3ba48c5d38ba3f90d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Settings.cs
uploadId: 997018
@@ -0,0 +1,182 @@
using UnityEngine;
namespace CharacterMovement
{
public partial class PlayerController
{
private float _originalHeight;
private Vector3 _originalCenter;
private float _targetCapsuleHeight;
private Vector3 _targetCapsuleCenter;
private bool _hasPendingStandRequest;
private readonly Collider[] _stanceOverlapBuffer = new Collider[16];
public float OriginalCapsuleHeight => _originalHeight;
public Vector3 OriginalCapsuleCenter => _originalCenter;
public bool TrySetStance(PlayerStance stance)
{
if (stance == CurrentStance)
return true;
float targetHeight = GetCapsuleHeightForStance(stance);
if (targetHeight > CapsuleCollider.height && !HasCapsuleClearance(targetHeight))
{
_hasPendingStandRequest = stance == PlayerStance.Standing;
return false;
}
PlayerStance previousStance = CurrentStance;
CurrentStance = stance;
_targetCapsuleHeight = targetHeight;
_targetCapsuleCenter = GetCapsuleCenterForHeight(targetHeight);
_hasPendingStandRequest = false;
StanceChanged?.Invoke(previousStance, CurrentStance);
if (CurrentState is IGroundLocomotionState)
SwitchToBaseGroundLocomotion();
return true;
}
public bool TryStand() => TrySetStance(PlayerStance.Standing);
public bool TryCrouch()
{
return IsCapabilityAllowed(MovementCapability.Crouch) && TrySetStance(PlayerStance.Crouching);
}
public bool TryProne()
{
return IsCapabilityAllowed(MovementCapability.Prone) && TrySetStance(PlayerStance.Prone);
}
public void SetTemporaryCapsuleHeight(float height)
{
float clampedHeight = Mathf.Clamp(height, CapsuleCollider.radius * 2f, _originalHeight);
_targetCapsuleHeight = clampedHeight;
_targetCapsuleCenter = GetCapsuleCenterForHeight(clampedHeight);
}
private void OnCrouch()
{
if (CurrentState is not IGroundLocomotionState)
return;
if (CanStartSlide())
{
BeginSlide();
return;
}
TryCrouch();
}
private void OnProne()
{
if (CurrentState is not IGroundLocomotionState)
return;
if (CurrentStance == PlayerStance.Prone)
TryStand();
else
TryProne();
}
private void UpdateStanceFromInput()
{
if (CurrentState is PlayerSlideState)
return;
if (InputSource.IsProne)
{
if (CurrentStance != PlayerStance.Prone && CurrentState is IGroundLocomotionState)
TryProne();
return;
}
if (CurrentStance == PlayerStance.Prone)
{
TryStand();
return;
}
if (InputSource.IsCrouching)
{
if (CurrentStance == PlayerStance.Standing && CurrentState is IGroundLocomotionState)
TryCrouch();
return;
}
if (CurrentStance == PlayerStance.Crouching || _hasPendingStandRequest)
TryStand();
}
private void UpdateCapsuleStance(float deltaTime)
{
if (!CapsuleCollider)
return;
float lerp = StanceTransitionSpeed <= 0f ? 1f : Mathf.Clamp01(StanceTransitionSpeed * deltaTime);
CapsuleCollider.height = Mathf.Lerp(CapsuleCollider.height, _targetCapsuleHeight, lerp);
CapsuleCollider.center = Vector3.Lerp(CapsuleCollider.center, _targetCapsuleCenter, lerp);
}
private float GetCapsuleHeightForStance(PlayerStance stance)
{
switch (stance)
{
case PlayerStance.Prone:
return Mathf.Clamp(ProneCapsuleHeight, CapsuleCollider.radius * 2f, _originalHeight);
case PlayerStance.Crouching:
return Mathf.Clamp(CrouchCapsuleHeight, CapsuleCollider.radius * 2f, _originalHeight);
default:
return _originalHeight;
}
}
private Vector3 GetCapsuleCenterForHeight(float height)
{
return new Vector3(_originalCenter.x, height * 0.5f, _originalCenter.z);
}
private bool HasCapsuleClearance(float targetHeight)
{
return HasCapsuleClearanceAt(RigidBody.position, targetHeight);
}
private bool HasCapsuleClearanceAt(Vector3 rootPosition, float targetHeight)
{
float radius = Mathf.Max(0.01f, CapsuleCollider.radius * StanceClearanceRadiusScale);
float halfHeight = Mathf.Max(targetHeight * 0.5f, radius);
float segment = Mathf.Max(0f, halfHeight - radius);
Vector3 center = rootPosition + GetCapsuleCenterForHeight(targetHeight);
Vector3 top = center + Vector3.up * segment;
Vector3 bottom = center - Vector3.up * segment;
LayerMask mask = GroundLayerMask | StairsLayerMask;
int hitCount = Physics.OverlapCapsuleNonAlloc(
bottom,
top,
radius,
_stanceOverlapBuffer,
mask,
QueryTriggerInteraction.Ignore);
for (int i = 0; i < hitCount; i++)
{
Collider hit = _stanceOverlapBuffer[i];
if (!hit || hit == CapsuleCollider || hit.transform.IsChildOf(transform))
continue;
return false;
}
return true;
}
private bool IsSelfCollider(Collider hit)
{
return hit && (hit == CapsuleCollider || hit.transform == transform || hit.transform.IsChildOf(transform));
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: e3af760aa5f14aa9a9f0bbd780e205dd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Stance.cs
uploadId: 997018
@@ -0,0 +1,102 @@
using UnityEngine;
namespace CharacterMovement
{
public readonly struct VaultTarget
{
public VaultTarget(Vector3 startPosition, Vector3 endPosition, Vector3 travelDirection)
{
StartPosition = startPosition;
EndPosition = endPosition;
TravelDirection = travelDirection;
}
public Vector3 StartPosition { get; }
public Vector3 EndPosition { get; }
public Vector3 TravelDirection { get; }
}
public partial class PlayerController
{
public bool TryStartVault()
{
if (!TryGetVaultTarget(out VaultTarget target))
return false;
SwitchState(new VaultingState(this, target));
return true;
}
public bool TryGetVaultTarget(out VaultTarget target)
{
target = default;
if (!CanMove || !IsCapabilityAllowed(MovementCapability.Vault)
|| VaultCooldown > 0f || CurrentStance != PlayerStance.Standing || !IsGrounded())
return false;
Vector3 direction = CalculateMovement();
direction = Vector3.ProjectOnPlane(direction, Vector3.up);
if (direction.sqrMagnitude <= 0.0001f)
return false;
direction.Normalize();
Vector3 rootPosition = RigidBody.position;
Vector3 capsuleCenter = transform.TransformPoint(CapsuleCollider.center);
float footY = capsuleCenter.y - CapsuleCollider.height * 0.5f;
float probeRadius = Mathf.Max(0.03f, CapsuleCollider.radius * VaultProbeRadiusScale);
float obstacleProbeHeight = Mathf.Clamp(
(VaultMinHeight + VaultMaxHeight) * 0.5f,
CapsuleCollider.radius + 0.05f,
CapsuleCollider.height - CapsuleCollider.radius);
Vector3 obstacleOrigin = new Vector3(capsuleCenter.x, footY + obstacleProbeHeight, capsuleCenter.z);
if (!Physics.SphereCast(
obstacleOrigin,
probeRadius,
direction,
out RaycastHit obstacleHit,
VaultForwardCheckDistance,
SurfaceProbeMask,
QueryTriggerInteraction.Ignore))
{
return false;
}
if (IsSelfCollider(obstacleHit.collider))
return false;
float topProbeY = footY + VaultMaxHeight + 0.35f;
Vector3 topProbeOrigin = obstacleHit.point + direction * 0.25f;
topProbeOrigin.y = topProbeY;
float topProbeDistance = Mathf.Max(0.1f, topProbeY - footY + 0.2f);
if (!Physics.Raycast(topProbeOrigin, Vector3.down, out RaycastHit topHit, topProbeDistance, SurfaceProbeMask, QueryTriggerInteraction.Ignore))
return false;
float obstacleHeight = topHit.point.y - footY;
if (obstacleHeight < VaultMinHeight || obstacleHeight > VaultMaxHeight)
return false;
Vector3 landingProbeOrigin = topHit.point + direction * VaultLandingForwardOffset + Vector3.up * 0.5f;
float landingProbeDistance = VaultMaxHeight + 1.5f;
Vector3 landingPoint = topHit.point;
if (Physics.Raycast(landingProbeOrigin, Vector3.down, out RaycastHit landingHit, landingProbeDistance, SurfaceProbeMask, QueryTriggerInteraction.Ignore)
&& !IsSelfCollider(landingHit.collider))
{
landingPoint = landingHit.point;
}
Vector3 endPosition = new Vector3(
landingProbeOrigin.x,
landingPoint.y + VaultGroundOffset,
landingProbeOrigin.z);
if (!HasCapsuleClearanceAt(endPosition, OriginalCapsuleHeight))
return false;
target = new VaultTarget(rootPosition, endPosition, direction);
return true;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 74a8c0464fe945b5b59f9e36a0b7d50f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.Vaulting.cs
uploadId: 997018
@@ -0,0 +1,661 @@
using System;
using UnityEngine;
namespace CharacterMovement
{
public enum PlayerStance
{
Standing,
Crouching,
Prone
}
public partial class PlayerController : StateController
{
[Header("References")]
[field: SerializeField]
[field: Tooltip("Rigidbody the motor drives. Added automatically if missing.")]
public Rigidbody RigidBody { get; private set; }
[field: SerializeField]
[field: Tooltip("Default input source. Added automatically if missing. To drive the character "
+ "from your own input stack, AI or network code instead, assign an "
+ "ICharacterInputSource under Advanced.")]
public InputHandler InputHandler { get; private set; }
[field: SerializeField]
[field: Tooltip("Collider used for grounding, step and clearance probes. Added automatically "
+ "if missing.")]
public CapsuleCollider CapsuleCollider { get; private set; }
[field: SerializeField]
[field: Tooltip("Optional. Only used as a fallback reference for CharacterAnimatorBridge; the "
+ "controller works fine without an Animator.")]
public Animator PlayerAnimator { get; private set; }
[Header("Preset")]
[field: SerializeField]
[field: Tooltip("Optional tuning preset. When assigned, its values overwrite the movement "
+ "settings below at edit time and on start, so one asset can re-feel the "
+ "character. Leave empty to tune this character directly.")]
public CharacterMotorSettings MotorSettings { get; private set; }
[Header("Movement")]
[field: SerializeField, Min(0f)]
[field: Tooltip("Default ground speed, used when neither walk nor sprint is held.")]
public float Speed { get; private set; } = 5f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Target speed while the walk modifier is held. Lower than Speed.")]
public float WalkSpeed { get; private set; } = 2f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How quickly the character reaches its target speed, in m/s squared. "
+ "Higher is snappier; lower feels heavier.")]
public float GroundAcceleration { get; private set; } = 38f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How quickly the character slows down when input stops, in m/s squared. "
+ "Usually a little higher than Ground Acceleration so stopping feels crisp.")]
public float GroundDeceleration { get; private set; } = 44f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How fast the character turns to face its movement direction. Only used by "
+ "third-person style facing; ignored when movement facing is disabled.")]
public float RotationDamping { get; private set; } = 10f;
[Header("Sprint")]
[field: SerializeField]
[field: Tooltip("Turn sprinting off entirely for this character. Gameplay systems can also "
+ "deny it at runtime with MovementCapability.Sprint.")]
public bool AllowSprint { get; private set; } = true;
[field: SerializeField]
[field: Tooltip("Hold: sprint only while the input is held. Toggle: a press switches "
+ "sprinting on and off, and releasing the movement input ends it.")]
public SprintActivationMode SprintActivation { get; private set; } = SprintActivationMode.Hold;
[field: SerializeField, Min(0f)]
[field: Tooltip("Target speed while sprinting. This is an absolute speed, not a bonus added "
+ "to Speed.")]
public float SprintSpeed { get; private set; } = 8f;
[Header("Jump")]
[field: SerializeField]
[field: Tooltip("Turn jumping off entirely for this character. Gameplay systems can also "
+ "deny it at runtime with MovementCapability.Jump.")]
public bool AllowJump { get; private set; } = true;
[field: SerializeField, Min(0f)]
[field: Tooltip("Upward speed applied at launch, in m/s. Jump height is roughly "
+ "(force * force) / (2 * gravity).")]
public float JumpingForce { get; private set; } = 8f;
[field: SerializeField]
[field: Tooltip("Releasing the jump button while rising cuts the jump short, so a tap gives a "
+ "small hop and a hold gives full height. Needs an input source that reports "
+ "IsJumpHeld; buffered and scripted jumps always reach full height.")]
public bool VariableJumpHeight { get; private set; } = true;
[field: SerializeField, Range(0.05f, 1f)]
[field: Tooltip("How much upward speed survives an early jump release. 1 disables the cut.")]
public float JumpCutMultiplier { get; private set; } = 0.5f;
[field: SerializeField]
[field: Tooltip("Allows steering while airborne. Turn off for a committed, arcade-style jump.")]
public bool CanMoveWhileJumping { get; private set; } = true;
[field: SerializeField, Min(0f)]
[field: Tooltip("Grace period after walking off a ledge during which a jump still works. "
+ "Around 0.1-0.2s feels forgiving without feeling floaty.")]
public float CoyoteTime { get; private set; } = 0.15f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How long a jump press is remembered. If the player presses jump just before "
+ "landing, the jump fires on touchdown instead of being dropped.")]
public float JumpBufferTime { get; private set; } = 0.12f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How long a jump press stays available to traversal actions such as vaulting. "
+ "Traversal is offered before a plain jump while this is active.")]
public float ParkourBufferTime { get; private set; } = 0.12f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How quickly the character reaches its target speed while airborne. Much "
+ "lower than Ground Acceleration in most games.")]
public float AirAcceleration { get; private set; } = 12f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How quickly airborne speed bleeds off with no input. Low values preserve "
+ "jump momentum.")]
public float AirDeceleration { get; private set; } = 2f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Protected window right after launch where ground stick, ground snapping and "
+ "coyote refresh stay off so the jump cannot be cancelled by the ground the "
+ "character is still next to. Raise it only if jumps are being swallowed.")]
public float JumpGraceDuration { get; private set; } = 0.08f;
[Header("Gravity")]
[field: SerializeField, Min(0.01f)]
[field: Tooltip("Scales Physics.gravity for this character only. Above 1 gives a heavier, "
+ "faster arc without changing project physics.")]
public float GravityScale { get; private set; } = 1f;
[field: SerializeField, Min(1f)]
[field: Tooltip("Extra gravity while falling, on top of Gravity Scale. Above 1 makes the fall "
+ "snappier than the rise, which most action games want. 1 keeps a pure arc.")]
public float FallGravityMultiplier { get; private set; } = 1f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Terminal velocity, in m/s. Caps fall speed so long drops stay controllable "
+ "and do not tunnel through thin floors.")]
public float MaxFallSpeed { get; private set; } = 28f;
[Header("Crouch & Stance")]
[field: SerializeField]
[field: Tooltip("Turn crouching off entirely for this character.")]
public bool AllowCrouch { get; private set; } = true;
[field: SerializeField]
[field: Tooltip("Turn prone off entirely for this character.")]
public bool AllowProne { get; private set; } = true;
[field: SerializeField, Min(0f)]
[field: Tooltip("Target speed while crouched.")]
public float CrouchSpeed { get; private set; } = 2.4f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Target speed while prone.")]
public float ProneSpeed { get; private set; } = 1.2f;
[field: SerializeField, Min(0.1f)]
[field: Tooltip("Capsule height while crouched. Must clear the obstacles you expect the "
+ "character to crouch under.")]
public float CrouchCapsuleHeight { get; private set; } = 1.15f;
[field: SerializeField, Min(0.1f)]
[field: Tooltip("Capsule height while prone.")]
public float ProneCapsuleHeight { get; private set; } = 0.55f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How fast the capsule resizes between stances. Higher is snappier; 0 snaps "
+ "instantly.")]
public float StanceTransitionSpeed { get; private set; } = 14f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How far above the head to check for ceilings. Stops upward velocity on "
+ "impact so the character does not stick to low roofs.")]
public float CeilingCheckDistance { get; private set; } = 0.05f;
[field: SerializeField, Range(0.5f, 1f)]
[field: Tooltip("Width of the ceiling probe as a fraction of the capsule radius. Slightly "
+ "under 1 stops the character bumping its head on walls it is brushing.")]
public float CeilingProbeRadiusScale { get; private set; } = 0.95f;
[field: SerializeField, Range(0.5f, 1f)]
[field: Tooltip("Width of the stand-up clearance check as a fraction of the capsule radius. "
+ "Lower it slightly if the character refuses to stand in tight spaces it "
+ "should fit in.")]
public float StanceClearanceRadiusScale { get; private set; } = 0.95f;
[Header("Ground Detection")]
[field: SerializeField]
[field: Tooltip("Layers treated as walkable ground. Must not include the character's own "
+ "layer. Leave empty to fall back to Default.")]
public LayerMask GroundLayerMask { get; private set; }
[field: SerializeField]
[field: Tooltip("Layers treated as stairs, which use the more forgiving Max Stairs Angle. "
+ "Leave empty to reuse Ground Layer Mask.")]
public LayerMask StairsLayerMask { get; private set; }
[field: SerializeField, Min(0.01f)]
[field: Tooltip("How far below the feet still counts as grounded. Small values make jumps "
+ "crisp; large values can make the character appear to float.")]
public float GroundCheckDistance { get; private set; } = 0.15f;
[field: SerializeField, Range(0.5f, 1f)]
[field: Tooltip("Ground probe width as a fraction of the capsule radius. Slightly under 1 "
+ "avoids catching on walls the character is brushing against.")]
public float GroundProbeRadiusScale { get; private set; } = 0.95f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How far the character is pulled down to stay attached when walking over "
+ "crests and down stairs. 0 disables snapping.")]
public float GroundSnapDistance { get; private set; } = 0.18f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Downward acceleration applied while grounded to keep contact on slopes and "
+ "moving platforms. Never applied while rising, so it cannot eat a jump.")]
public float GroundStickForce { get; private set; } = 24f;
[field: SerializeField]
[field: Tooltip("Casts extra downward rays around the capsule as well as the main sweep. "
+ "Keeps footing on grates, stair noses and narrow ledges the sweep misses. "
+ "Turn off to save six raycasts per physics step on simple geometry.")]
public bool UseSupplementaryGroundRays { get; private set; } = true;
[field: SerializeField, Range(0f, 1f)]
[field: Tooltip("How far the supplementary rays sit from the capsule centre, as a fraction "
+ "of the probe radius. Wider catches more ledge edges but can find ground "
+ "the character is not really over.")]
public float SupplementaryRaySpread { get; private set; } = 0.3f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How far the ground probe starts above the capsule before sweeping down. "
+ "Prevents the sweep starting inside a surface the character is resting on.")]
public float GroundProbeLiftOffset { get; private set; } = 0.05f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Extra reach added to the probe rays, absorbing float error at contact.")]
public float GroundProbeEpsilon { get; private set; } = 0.05f;
[Header("Slopes & Steps")]
[field: SerializeField, Range(0, 90)]
[field: Tooltip("Steepest surface the character can stand and walk on. Anything steeper is "
+ "treated as a slide.")]
public float MaxSlopeAngle { get; private set; } = 45f;
[field: SerializeField, Range(0, 90)]
[field: Tooltip("Steepest walkable angle for colliders on the Stairs layer. Usually higher "
+ "than Max Slope Angle so stair edges stay walkable.")]
public float MaxStairsAngle { get; private set; } = 60f;
[field: SerializeField, Min(0.01f)]
[field: Tooltip("Tallest step the character can climb without jumping.")]
public float StepHeight { get; private set; } = 0.35f;
[field: SerializeField, Min(0.01f)]
[field: Tooltip("How far ahead to look for a step. Increase if the character catches on "
+ "stair noses at high speed.")]
public float StepCheckDistance { get; private set; } = 0.2f;
[field: SerializeField, Range(0.1f, 1f)]
[field: Tooltip("Step probe width as a fraction of the capsule radius.")]
public float StepProbeRadiusScale { get; private set; } = 0.85f;
[field: SerializeField, Range(0.1f, 2f)]
[field: Tooltip("Speed scale when moving uphill. Below 1 makes climbs feel like effort.")]
public float UphillSlopeSpeedMultiplier { get; private set; } = 0.9f;
[field: SerializeField, Range(0.1f, 2f)]
[field: Tooltip("Speed scale when moving downhill. Slightly above 1 adds momentum.")]
public float DownhillSlopeSpeedMultiplier { get; private set; } = 1.05f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Acceleration pulling the character down slopes steeper than Max Slope Angle.")]
public float SlideForce { get; private set; } = 15f;
[field: SerializeField]
[field: Tooltip("Tilts the character to match the slope it is standing on. Suits third-person "
+ "characters; usually turned off for first-person.")]
public bool AlignToSlopeNormal { get; private set; } = true;
[field: SerializeField, Min(0f)]
[field: Tooltip("How fast the character tilts toward the slope normal when Align To Slope "
+ "Normal is on.")]
public float Alignment { get; private set; } = 5f;
[Header("Abilities: Dash")]
[field: SerializeField]
[field: Tooltip("Turn dashing off entirely for this character.")]
public bool AllowDash { get; private set; } = true;
[field: SerializeField, Min(0f)]
[field: Tooltip("How long a dash lasts.")]
public float DashDuration { get; private set; } = 0.2f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Distance covered by one dash.")]
public float DashLength { get; private set; } = 5f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Delay before another dash is allowed.")]
public float DashCooldownDuration { get; private set; } = 3f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Downward speed added when dashing out of a jump, as a fraction of Jumping "
+ "Force. Gives an air dash a downward slam. 0 keeps the dash level.")]
public float AirDashDownwardBoost { get; private set; } = 0.5f;
[Header("Abilities: Slide")]
[field: SerializeField]
[field: Tooltip("Turn input slides off entirely. Involuntary sliding down steep slopes is "
+ "controlled by Max Slope Angle and is not affected by this.")]
public bool AllowSlide { get; private set; } = true;
[field: SerializeField, Min(0.05f)]
[field: Tooltip("How long a slide lasts before returning to normal locomotion.")]
public float SlideDuration { get; private set; } = 0.75f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Speed at the start of a slide.")]
public float SlideStartSpeed { get; private set; } = 9f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Speed at the end of a slide. The slide eases from start to end speed.")]
public float SlideEndSpeed { get; private set; } = 2.5f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How much the player can steer mid-slide. 0 locks the direction.")]
public float SlideSteeringStrength { get; private set; } = 0.35f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Delay before another slide is allowed.")]
public float SlideCooldownDuration { get; private set; } = 0.5f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Minimum speed required to start a slide, so crouching while walking does "
+ "not slide.")]
public float MinimumSlideInputSpeed { get; private set; } = 5.5f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Speed cap while sliding down a slope too steep to stand on, so long steep "
+ "drops do not accelerate the character indefinitely.")]
public float MaxSlopeSlideSpeed { get; private set; } = 10f;
[Header("Abilities: Vault")]
[field: SerializeField]
[field: Tooltip("Turn vaulting off entirely for this character.")]
public bool AllowVault { get; private set; } = true;
[field: SerializeField, Min(0.05f)]
[field: Tooltip("How long the vault movement takes.")]
public float VaultDuration { get; private set; } = 0.36f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Extra height added mid-vault to arc over the obstacle.")]
public float VaultArcHeight { get; private set; } = 0.32f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Delay before another vault is allowed.")]
public float VaultCooldownDuration { get; private set; } = 0.2f;
[field: SerializeField, Min(0.01f)]
[field: Tooltip("How far ahead to look for a vaultable obstacle.")]
public float VaultForwardCheckDistance { get; private set; } = 1.05f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How far past the obstacle the character lands.")]
public float VaultLandingForwardOffset { get; private set; } = 1.05f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Obstacles shorter than this are stepped over instead of vaulted.")]
public float VaultMinHeight { get; private set; } = 0.25f;
[field: SerializeField, Min(0.01f)]
[field: Tooltip("Obstacles taller than this cannot be vaulted. Keep below the standing "
+ "capsule height.")]
public float VaultMaxHeight { get; private set; } = 1.1f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Vault probe width as a fraction of the capsule radius.")]
public float VaultProbeRadiusScale { get; private set; } = 0.75f;
[field: SerializeField, Min(0f)]
[field: Tooltip("How far above the landing surface the character is placed when a vault "
+ "finishes, so it does not end the vault inside the floor.")]
public float VaultGroundOffset { get; private set; } = 0.02f;
[Header("Advanced")]
[field: SerializeField, Min(0f)]
[field: Tooltip("How quickly external pushes from AddImpulse and SetExternalVelocity bleed "
+ "off, in m/s squared. Lower values make knockback carry further.")]
public float ExternalForceDrag { get; private set; } = 5f;
[field: SerializeField]
[field: Tooltip("Applies the Rigidbody settings below on start. Turn off to keep whatever "
+ "you configured on the Rigidbody yourself.")]
public bool ConfigureRigidbodyOnStart { get; private set; } = true;
[field: SerializeField]
[field: Tooltip("Interpolation applied on start. Interpolate keeps motion smooth when the "
+ "frame rate and physics rate differ.")]
public RigidbodyInterpolation RigidbodyInterpolation { get; private set; } =
UnityEngine.RigidbodyInterpolation.Interpolate;
[field: SerializeField]
[field: Tooltip("Collision detection applied on start. Continuous Dynamic stops fast falls "
+ "tunnelling through thin floors.")]
public CollisionDetectionMode RigidbodyCollisionDetection { get; private set; } =
CollisionDetectionMode.ContinuousDynamic;
[field: SerializeField, Min(0f)]
[field: Tooltip("Upward speed above which a grounded character is considered launched and "
+ "hands over to the airborne state immediately, without waiting for coyote "
+ "time. Affects knockback and launch pads.")]
public float AirborneLaunchVelocityThreshold { get; private set; } = 0.1f;
[field: SerializeField, Min(0f)]
[field: Tooltip("Downward speed below which the character is considered to be falling, used "
+ "to raise the falling event. Small values react sooner.")]
public float FallDetectionVelocityThreshold { get; private set; } = 0.05f;
public float DashCooldown { get; set; }
public float SlideCooldown { get; set; }
public float VaultCooldown { get; set; }
public float SpeedMultiplier { get; set; } = 1f;
public PlayerStance CurrentStance { get; private set; } = PlayerStance.Standing;
public event Action FallingEvent;
public event Action JumpStarted;
public event Action Landed;
public event Action SlideStarted;
public event Action SlideEnded;
public event Action VaultStarted;
public event Action VaultEnded;
public event Action MantleStarted;
public event Action MantleEnded;
public event Action<PlayerStance, PlayerStance> StanceChanged;
public Transform MainCameraTransform { get; private set; }
private static PhysicsMaterial _sharedFrictionlessMaterial;
private float _nextMainCameraRefreshTime;
private bool _fallingEventLatched;
private void OnValidate()
{
ApplyMotorSettings();
ValidateMotorValues();
}
private void Start()
{
ApplyMotorSettings();
ValidateMotorValues();
InitializeInputSource();
if (!CapsuleCollider)
CapsuleCollider = GetComponent<CapsuleCollider>() ?? gameObject.AddComponent<CapsuleCollider>();
if (!RigidBody)
RigidBody = GetComponent<Rigidbody>() ?? gameObject.AddComponent<Rigidbody>();
RigidBody.freezeRotation = true;
if (ConfigureRigidbodyOnStart)
{
RigidBody.interpolation = RigidbodyInterpolation;
RigidBody.collisionDetectionMode = RigidbodyCollisionDetection;
}
if (GroundLayerMask.value == 0)
GroundLayerMask = LayerMask.GetMask("Default");
if (StairsLayerMask.value == 0)
StairsLayerMask = GroundLayerMask;
if (lockCursorOnStart)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
if (mainCameraTransform)
SetMainCameraTransform(mainCameraTransform);
RefreshMainCameraReference(true);
if (!MainCameraTransform)
MainCameraTransform = transform;
_originalCenter = CapsuleCollider.center;
_originalHeight = CapsuleCollider.height;
_targetCapsuleHeight = _originalHeight;
_targetCapsuleCenter = _originalCenter;
CapsuleCollider.material = GetSharedFrictionlessMaterial();
StateChanged += OnStateChangedDebug;
StateChanged += OnMovementStateChanged;
InitializeSkillModules();
_coyoteTimer = CoyoteTime;
_slopeAlignmentEnabled = AlignToSlopeNormal;
SwitchState(new IdleState(this));
_debugCurrentStateName = CurrentState?.GetType().Name ?? "None";
_debugLastStateChangeTime = Time.time;
}
private void OnDestroy()
{
UnsubscribeFromInputSource();
ClearMovementModifiers();
StateChanged -= OnStateChangedDebug;
StateChanged -= OnMovementStateChanged;
CleanupSkillModules();
}
private static PhysicsMaterial GetSharedFrictionlessMaterial()
{
if (_sharedFrictionlessMaterial)
return _sharedFrictionlessMaterial;
_sharedFrictionlessMaterial = new PhysicsMaterial("MotionCore_Frictionless")
{
hideFlags = HideFlags.HideAndDontSave,
dynamicFriction = 0f,
staticFriction = 0f,
bounciness = 0f,
frictionCombine = PhysicsMaterialCombine.Minimum,
bounceCombine = PhysicsMaterialCombine.Minimum
};
return _sharedFrictionlessMaterial;
}
protected override void PreStateUpdate(float deltaTime)
{
EvaluateMovementModifiers();
UpdateSprintActivation();
RefreshObservableState();
}
protected override void PreStateFixedUpdate(float deltaTime)
{
BeginGroundProbeStep();
EvaluateMovementModifiers();
}
protected override void CustomUpdate(float deltaTime)
{
if (DashCooldown > 0f)
DashCooldown -= deltaTime;
if (SlideCooldown > 0f)
SlideCooldown -= deltaTime;
if (VaultCooldown > 0f)
VaultCooldown -= deltaTime;
TickBufferedInputs(deltaTime);
UpdateStanceFromInput();
UpdateCapsuleStance(deltaTime);
UpdateCoyoteTimer(deltaTime);
RefreshMainCameraReference();
UpdateSkillModules(deltaTime);
}
protected override void CustomFixedUpdate(float deltaTime)
{
TickJumpGrace(deltaTime);
ApplyVariableJumpHeight();
ApplyFallGravity(deltaTime);
DecayExternalVelocity(deltaTime);
UpdateGroundStickSuppression(deltaTime);
ApplyGravityScale(deltaTime);
ClampFallSpeed();
if (_groundProbingEnabled)
{
UpdatePlatformMotion(deltaTime);
bool isGrounded = IsGrounded();
_debugLastIsGrounded = isGrounded;
NotifyFallingIfNeeded(isGrounded);
HandleCeilingCollision();
if (!isGrounded && TrySnapToGround())
isGrounded = true;
if (_slopeAlignmentEnabled && isGrounded)
AlignToSurface(deltaTime);
if (ShouldApplyGroundStick(isGrounded))
RigidBody.AddForce(Vector3.down * GroundStickForce, ForceMode.Acceleration);
}
else
{
_platformVelocity = Vector3.zero;
ResetPlatformTracking();
_debugLastIsGrounded = false;
_debugHasSurfaceHit = false;
_debugSupplementaryRayCount = 0;
InvalidateGroundProbeCache();
}
FixedUpdateSkillModules(deltaTime);
}
/// <summary>
/// Ground stick only helps while the character is settling onto or running along a surface.
/// Applying it during an ascent silently eats a large part of the jump velocity.
/// </summary>
private bool ShouldApplyGroundStick(bool isGrounded)
{
return isGrounded
&& GroundStickForce > 0f
&& CanApplyGroundStick
&& !IsJumpGraceActive
&& RigidBody.linearVelocity.y <= 0.01f;
}
/// <summary>
/// Raises <see cref="FallingEvent"/> once per fall instead of once per physics step.
/// The latch is released on landing and whenever the active state changes, so a state
/// entered mid-fall still receives the notification it needs to hand over to falling.
/// </summary>
private void NotifyFallingIfNeeded(bool isGrounded)
{
bool isFalling = RigidBody.linearVelocity.y < -FallDetectionVelocityThreshold
&& !isGrounded
&& !IsCoyoteTimeActive;
if (!isFalling)
{
_fallingEventLatched = false;
return;
}
if (_fallingEventLatched)
return;
_fallingEventLatched = true;
FallingEvent?.Invoke();
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 6996d94b5d6e41a19dc870ec636ec3f5
timeCreated: 1701807625
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/PlayerController.cs
uploadId: 997018
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 46bebe3cdb212a74ebbc4cb892a43ff1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,69 @@
using UnityEngine;
namespace CharacterMovement
{
public class DoubleJumpModule : SkillModule
{
[Tooltip("Upward speed applied by each extra jump, in m/s.")]
[SerializeField] private float doubleJumpForce = 8f;
[Tooltip("How many extra mid-air jumps are granted between landings. 1 gives a classic double "
+ "jump.")]
[SerializeField] private int maxExtraJumps = 1;
private int _remainingExtraJumps;
private bool _canConsumeExtraJump;
protected override void OnInitialize()
{
PlayerController.StateChanged += OnStateChanged;
}
protected override void OnCleanup()
{
if (!PlayerController)
return;
PlayerController.StateChanged -= OnStateChanged;
}
public override void FixedUpdateModule(float deltaTime)
{
if (!_canConsumeExtraJump
|| _remainingExtraJumps <= 0
|| !PlayerController.HasBufferedJumpIntent
|| PlayerController.IsGrounded()
|| PlayerController.IsCoyoteTimeActive)
{
return;
}
ConsumeExtraJump();
}
private void OnStateChanged(State previousState, State nextState)
{
if (nextState is IGroundLocomotionState)
{
_remainingExtraJumps = maxExtraJumps;
_canConsumeExtraJump = false;
return;
}
// Any airborne state arms the extra jump; landing in a ground state refills it.
if (nextState is JumpingState || nextState is FallingState)
_canConsumeExtraJump = true;
}
private void ConsumeExtraJump()
{
_remainingExtraJumps--;
PlayerController.ClearBufferedInputs();
Vector3 velocity = PlayerController.RigidBody.linearVelocity;
velocity.y = Mathf.Max(0f, doubleJumpForce);
PlayerController.RigidBody.linearVelocity = velocity;
PlayerController.SwitchState(new JumpingState(PlayerController));
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b2b232ab95ec511469c5fa46cba36b6b
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/PlayerMovement/Skills/DoubleJumpModule.cs
uploadId: 997018