Import assets from store
This commit is contained in:
1 parent
a05f2e47a2
commit
376e52e323
875 files changed
+128037
No files matched your search
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ee2dcf4cd72c4e48a8b0153c89b3d2be
|
||||
timeCreated: 1701807598
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace CharacterMovement
|
||||
{
|
||||
/// <summary>
|
||||
/// Shared base for every <see cref="PlayerController"/> state.
|
||||
/// States hold the controller reference here instead of inheriting it from another concrete
|
||||
/// state, so an airborne or transient state is never mistaken for a ground locomotion state.
|
||||
/// </summary>
|
||||
public abstract class PlayerStateBase : State
|
||||
{
|
||||
protected readonly PlayerController _playerController;
|
||||
|
||||
protected PlayerStateBase(PlayerController playerController)
|
||||
{
|
||||
_playerController = playerController;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5c7f24c5660744f4b2ada22bdf013725
|
||||
timeCreated: 1757808000
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Abstracts/PlayerStateBase.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,25 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
public abstract class SkillModule : MonoBehaviour
|
||||
{
|
||||
protected PlayerController PlayerController { get; private set; }
|
||||
|
||||
internal void Initialize(PlayerController controller)
|
||||
{
|
||||
PlayerController = controller;
|
||||
OnInitialize();
|
||||
}
|
||||
|
||||
internal void Cleanup()
|
||||
{
|
||||
OnCleanup();
|
||||
}
|
||||
|
||||
protected virtual void OnInitialize() { }
|
||||
protected virtual void OnCleanup() { }
|
||||
public virtual void UpdateModule(float deltaTime) { }
|
||||
public virtual void FixedUpdateModule(float deltaTime) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 88e5dd8b58cb4cd40b185bc95c914321
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Abstracts/SkillModule.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace CharacterMovement
|
||||
{
|
||||
public abstract class State
|
||||
{
|
||||
public abstract void Enter();
|
||||
public abstract void UpdateState(float deltaTime);
|
||||
public abstract void FixedUpdateState(float deltaTime);
|
||||
public abstract void Exit();
|
||||
}
|
||||
|
||||
public interface IGroundLocomotionState { }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 37357d512a844e1b9b0b8d2db672aad0
|
||||
timeCreated: 1701807122
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Abstracts/State.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
public abstract class StateController : MonoBehaviour
|
||||
{
|
||||
private State _currentState;
|
||||
public State CurrentState => _currentState;
|
||||
|
||||
public event Action<State, State> StateChanged;
|
||||
|
||||
public void SwitchState(State newState)
|
||||
{
|
||||
var previous = _currentState;
|
||||
_currentState?.Exit();
|
||||
_currentState = newState;
|
||||
_currentState?.Enter();
|
||||
StateChanged?.Invoke(previous, _currentState);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
float deltaTime = Time.deltaTime;
|
||||
PreStateUpdate(deltaTime);
|
||||
_currentState?.UpdateState(deltaTime);
|
||||
CustomUpdate(deltaTime);
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
float deltaTime = Time.fixedDeltaTime;
|
||||
PreStateFixedUpdate(deltaTime);
|
||||
_currentState?.FixedUpdateState(deltaTime);
|
||||
CustomFixedUpdate(deltaTime);
|
||||
}
|
||||
|
||||
public abstract void Move(Vector3 moveDirection, float deltaTime, float additionalSpeed = 0);
|
||||
|
||||
/// <summary>Runs before the active state's update, for data states are about to read.</summary>
|
||||
protected virtual void PreStateUpdate(float deltaTime) { }
|
||||
|
||||
/// <summary>Runs before the active state's fixed update, for data states are about to read.</summary>
|
||||
protected virtual void PreStateFixedUpdate(float deltaTime) { }
|
||||
|
||||
protected abstract void CustomUpdate(float deltaTime);
|
||||
protected abstract void CustomFixedUpdate(float deltaTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3b692b9daa1058943ac92cf258d15008
|
||||
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/Abstracts/StateController.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2093622c41e344feb0fb78a49bba8849
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace CharacterMovement
|
||||
{
|
||||
public enum CharacterAnimationState
|
||||
{
|
||||
None = 0,
|
||||
Idle = 1,
|
||||
Moving = 2,
|
||||
Jumping = 3,
|
||||
Falling = 4,
|
||||
Crouching = 5,
|
||||
Prone = 6,
|
||||
Sliding = 7,
|
||||
Dashing = 8,
|
||||
Vaulting = 9,
|
||||
Parkour = 10
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 30e61f43d67947beb1e1d757f9e9ad19
|
||||
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/Animation/CharacterAnimationState.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,280 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
[AddComponentMenu("Character Controller/Core/Character Animator Bridge")]
|
||||
public class CharacterAnimatorBridge : MonoBehaviour
|
||||
{
|
||||
[System.Serializable]
|
||||
public class StanceChangedEvent : UnityEvent<PlayerStance, PlayerStance>
|
||||
{
|
||||
}
|
||||
|
||||
[Header("References")]
|
||||
[Tooltip("Controller to read state from. Found on this GameObject if left empty.")]
|
||||
[SerializeField] private PlayerController playerController;
|
||||
[Tooltip("Animator to drive. Searched for in children if left empty.")]
|
||||
[SerializeField] private Animator animator;
|
||||
[Tooltip("Asset mapping controller state to your Animator's parameter names.")]
|
||||
[SerializeField] private CharacterAnimatorParameters parameters;
|
||||
|
||||
[Header("Tuning")]
|
||||
[Tooltip("Smoothing applied to float parameters, in seconds. 0 writes raw values.")]
|
||||
[SerializeField, Min(0f)] private float floatDampTime = 0.08f;
|
||||
[Header("Events")]
|
||||
[Tooltip("Raised when a jump launches.")]
|
||||
[SerializeField] private UnityEvent jumpStarted;
|
||||
[Tooltip("Raised on touchdown.")]
|
||||
[SerializeField] private UnityEvent landed;
|
||||
[Tooltip("Raised when a slide begins.")]
|
||||
[SerializeField] private UnityEvent slideStarted;
|
||||
[Tooltip("Raised when a slide ends.")]
|
||||
[SerializeField] private UnityEvent slideEnded;
|
||||
[Tooltip("Raised when a vault begins.")]
|
||||
[SerializeField] private UnityEvent vaultStarted;
|
||||
[Tooltip("Raised when a vault ends.")]
|
||||
[SerializeField] private UnityEvent vaultEnded;
|
||||
[Tooltip("Raised when an add-on module reports a mantle starting.")]
|
||||
[SerializeField] private UnityEvent mantleStarted;
|
||||
[Tooltip("Raised when an add-on module reports a mantle ending.")]
|
||||
[SerializeField] private UnityEvent mantleEnded;
|
||||
[Tooltip("Raised when the stance changes, with the previous and new stance.")]
|
||||
[SerializeField] private StanceChangedEvent stanceChanged;
|
||||
|
||||
private readonly Dictionary<int, AnimatorControllerParameterType> _availableParameters =
|
||||
new Dictionary<int, AnimatorControllerParameterType>();
|
||||
|
||||
public PlayerController PlayerController => playerController;
|
||||
public Animator Animator => animator;
|
||||
public CharacterAnimatorParameters Parameters => parameters;
|
||||
public UnityEvent JumpStarted => jumpStarted;
|
||||
public UnityEvent Landed => landed;
|
||||
public UnityEvent SlideStarted => slideStarted;
|
||||
public UnityEvent SlideEnded => slideEnded;
|
||||
public UnityEvent VaultStarted => vaultStarted;
|
||||
public UnityEvent VaultEnded => vaultEnded;
|
||||
public UnityEvent MantleStarted => mantleStarted;
|
||||
public UnityEvent MantleEnded => mantleEnded;
|
||||
public StanceChangedEvent StanceChanged => stanceChanged;
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
ResolveReferences();
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
ResolveReferences();
|
||||
CacheAnimatorParameters();
|
||||
Subscribe();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
Unsubscribe();
|
||||
}
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
floatDampTime = Mathf.Max(0f, floatDampTime);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!playerController || !animator || !parameters)
|
||||
return;
|
||||
|
||||
float deltaTime = Time.deltaTime;
|
||||
Vector3 velocity = playerController.RigidBody ? playerController.RigidBody.linearVelocity : Vector3.zero;
|
||||
Vector3 planarVelocity = Vector3.ProjectOnPlane(velocity, Vector3.up);
|
||||
Vector2 moveInput = playerController.InputSource.MoveDirection;
|
||||
LocomotionState movementState = playerController.MovementState;
|
||||
|
||||
TrySetFloat(parameters.Speed, velocity.magnitude, deltaTime);
|
||||
float planarSpeed = planarVelocity.magnitude;
|
||||
TrySetFloat(parameters.PlanarSpeed, planarSpeed, deltaTime);
|
||||
TrySetFloat(parameters.NormalizedSpeed, ResolveNormalizedSpeed(planarSpeed), deltaTime);
|
||||
TrySetFloat(parameters.Forward, moveInput.y, deltaTime);
|
||||
TrySetFloat(parameters.Strafe, moveInput.x, deltaTime);
|
||||
TrySetBool(parameters.IsGrounded, playerController.IsGrounded());
|
||||
TrySetBool(parameters.IsFalling, movementState == LocomotionState.Falling);
|
||||
TrySetBool(parameters.IsJumping, movementState == LocomotionState.Jumping);
|
||||
TrySetBool(parameters.IsSprinting, playerController.IsSprintRequested);
|
||||
TrySetBool(parameters.IsCrouching, playerController.CurrentStance == PlayerStance.Crouching);
|
||||
TrySetBool(parameters.IsProne, playerController.CurrentStance == PlayerStance.Prone);
|
||||
TrySetBool(parameters.IsSliding, movementState == LocomotionState.Sliding);
|
||||
TrySetInt(parameters.Stance, (int)playerController.CurrentStance);
|
||||
TrySetInt(parameters.MovementState, (int)PlayerController.ToAnimationState(movementState));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Planar speed as a 0-1 fraction of the character's top speed, for blend trees.
|
||||
/// </summary>
|
||||
private float ResolveNormalizedSpeed(float planarSpeed)
|
||||
{
|
||||
float topSpeed = Mathf.Max(playerController.SprintSpeed, playerController.Speed);
|
||||
return topSpeed > 0.0001f ? Mathf.Clamp01(planarSpeed / topSpeed) : 0f;
|
||||
}
|
||||
|
||||
public void RefreshAnimatorParameterCache()
|
||||
{
|
||||
CacheAnimatorParameters();
|
||||
}
|
||||
|
||||
private void ResolveReferences()
|
||||
{
|
||||
if (!playerController)
|
||||
playerController = GetComponent<PlayerController>();
|
||||
|
||||
if (!animator)
|
||||
{
|
||||
if (playerController && playerController.PlayerAnimator)
|
||||
animator = playerController.PlayerAnimator;
|
||||
else
|
||||
animator = GetComponentInChildren<Animator>();
|
||||
}
|
||||
}
|
||||
|
||||
private void Subscribe()
|
||||
{
|
||||
if (!playerController)
|
||||
return;
|
||||
|
||||
playerController.JumpStarted += OnJumpStarted;
|
||||
playerController.Landed += OnLanded;
|
||||
playerController.SlideStarted += OnSlideStarted;
|
||||
playerController.SlideEnded += OnSlideEnded;
|
||||
playerController.VaultStarted += OnVaultStarted;
|
||||
playerController.VaultEnded += OnVaultEnded;
|
||||
playerController.MantleStarted += OnMantleStarted;
|
||||
playerController.MantleEnded += OnMantleEnded;
|
||||
playerController.StanceChanged += OnStanceChanged;
|
||||
}
|
||||
|
||||
private void Unsubscribe()
|
||||
{
|
||||
if (!playerController)
|
||||
return;
|
||||
|
||||
playerController.JumpStarted -= OnJumpStarted;
|
||||
playerController.Landed -= OnLanded;
|
||||
playerController.SlideStarted -= OnSlideStarted;
|
||||
playerController.SlideEnded -= OnSlideEnded;
|
||||
playerController.VaultStarted -= OnVaultStarted;
|
||||
playerController.VaultEnded -= OnVaultEnded;
|
||||
playerController.MantleStarted -= OnMantleStarted;
|
||||
playerController.MantleEnded -= OnMantleEnded;
|
||||
playerController.StanceChanged -= OnStanceChanged;
|
||||
}
|
||||
|
||||
private void CacheAnimatorParameters()
|
||||
{
|
||||
_availableParameters.Clear();
|
||||
if (!animator)
|
||||
return;
|
||||
|
||||
AnimatorControllerParameter[] animatorParameters = animator.parameters;
|
||||
for (int i = 0; i < animatorParameters.Length; i++)
|
||||
{
|
||||
AnimatorControllerParameter parameter = animatorParameters[i];
|
||||
_availableParameters[parameter.nameHash] = parameter.type;
|
||||
}
|
||||
}
|
||||
|
||||
private void TrySetFloat(string parameterName, float value, float deltaTime)
|
||||
{
|
||||
if (!TryGetParameter(parameterName, AnimatorControllerParameterType.Float, out int hash))
|
||||
return;
|
||||
|
||||
if (floatDampTime > 0f)
|
||||
animator.SetFloat(hash, value, floatDampTime, deltaTime);
|
||||
else
|
||||
animator.SetFloat(hash, value);
|
||||
}
|
||||
|
||||
private void TrySetBool(string parameterName, bool value)
|
||||
{
|
||||
if (TryGetParameter(parameterName, AnimatorControllerParameterType.Bool, out int hash))
|
||||
animator.SetBool(hash, value);
|
||||
}
|
||||
|
||||
private void TrySetInt(string parameterName, int value)
|
||||
{
|
||||
if (TryGetParameter(parameterName, AnimatorControllerParameterType.Int, out int hash))
|
||||
animator.SetInteger(hash, value);
|
||||
}
|
||||
|
||||
private void TrySetTrigger(string parameterName)
|
||||
{
|
||||
if (TryGetParameter(parameterName, AnimatorControllerParameterType.Trigger, out int hash))
|
||||
animator.SetTrigger(hash);
|
||||
}
|
||||
|
||||
private bool TryGetParameter(string parameterName, AnimatorControllerParameterType expectedType, out int hash)
|
||||
{
|
||||
hash = 0;
|
||||
if (string.IsNullOrWhiteSpace(parameterName) || !animator)
|
||||
return false;
|
||||
|
||||
hash = Animator.StringToHash(parameterName);
|
||||
return _availableParameters.TryGetValue(hash, out AnimatorControllerParameterType actualType)
|
||||
&& actualType == expectedType;
|
||||
}
|
||||
|
||||
private void OnJumpStarted()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.JumpStarted : null);
|
||||
jumpStarted?.Invoke();
|
||||
}
|
||||
|
||||
private void OnLanded()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.Landed : null);
|
||||
landed?.Invoke();
|
||||
}
|
||||
|
||||
private void OnSlideStarted()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.SlideStarted : null);
|
||||
slideStarted?.Invoke();
|
||||
}
|
||||
|
||||
private void OnSlideEnded()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.SlideEnded : null);
|
||||
slideEnded?.Invoke();
|
||||
}
|
||||
|
||||
private void OnVaultStarted()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.VaultStarted : null);
|
||||
vaultStarted?.Invoke();
|
||||
}
|
||||
|
||||
private void OnVaultEnded()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.VaultEnded : null);
|
||||
vaultEnded?.Invoke();
|
||||
}
|
||||
|
||||
private void OnMantleStarted()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.MantleStarted : null);
|
||||
mantleStarted?.Invoke();
|
||||
}
|
||||
|
||||
private void OnMantleEnded()
|
||||
{
|
||||
TrySetTrigger(parameters ? parameters.MantleEnded : null);
|
||||
mantleEnded?.Invoke();
|
||||
}
|
||||
|
||||
private void OnStanceChanged(PlayerStance previousStance, PlayerStance nextStance)
|
||||
{
|
||||
stanceChanged?.Invoke(previousStance, nextStance);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a2afa0f6808a4a2a86b4ef67fb9e913b
|
||||
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/Animation/CharacterAnimatorBridge.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,82 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
[CreateAssetMenu(menuName = "Character Controller/Core/Animator Parameters", fileName = "CharacterAnimatorParameters")]
|
||||
public class CharacterAnimatorParameters : ScriptableObject
|
||||
{
|
||||
[Header("Float Parameters")]
|
||||
[SerializeField] private string speed = "Speed";
|
||||
[SerializeField] private string planarSpeed = "PlanarSpeed";
|
||||
[SerializeField]
|
||||
[Tooltip("Planar speed as 0-1 of the character's top speed. Convenient as the blend "
|
||||
+ "parameter of an idle/walk/run/sprint blend tree.")]
|
||||
private string normalizedSpeed = "NormalizedSpeed";
|
||||
[SerializeField] private string forward = "Forward";
|
||||
[Tooltip("Float parameter receiving sideways move input, -1 to 1.")]
|
||||
[SerializeField] private string strafe = "Strafe";
|
||||
|
||||
[Header("Bool Parameters")]
|
||||
[Tooltip("Bool parameter set while the character is on the ground.")]
|
||||
[SerializeField] private string isGrounded = "IsGrounded";
|
||||
[Tooltip("Bool parameter set while the character is falling.")]
|
||||
[SerializeField] private string isFalling = "IsFalling";
|
||||
[Tooltip("Bool parameter set while the character is rising from a jump.")]
|
||||
[SerializeField] private string isJumping = "IsJumping";
|
||||
[Tooltip("Bool parameter set while sprinting.")]
|
||||
[SerializeField] private string isSprinting = "IsSprinting";
|
||||
[Tooltip("Bool parameter set while in the crouch stance.")]
|
||||
[SerializeField] private string isCrouching = "IsCrouching";
|
||||
[Tooltip("Bool parameter set while in the prone stance.")]
|
||||
[SerializeField] private string isProne = "IsProne";
|
||||
[Tooltip("Bool parameter set while sliding.")]
|
||||
[SerializeField] private string isSliding = "IsSliding";
|
||||
|
||||
[Header("Int Parameters")]
|
||||
[Tooltip("Int parameter receiving the PlayerStance value (0 standing, 1 crouching, 2 prone).")]
|
||||
[SerializeField] private string stance = "Stance";
|
||||
[Tooltip("Int parameter receiving the CharacterAnimationState value.")]
|
||||
[SerializeField] private string movementState = "MovementState";
|
||||
|
||||
[Header("Trigger Parameters")]
|
||||
[Tooltip("Trigger fired when a jump launches.")]
|
||||
[SerializeField] private string jumpStarted = "JumpStarted";
|
||||
[Tooltip("Trigger fired on touchdown.")]
|
||||
[SerializeField] private string landed = "Landed";
|
||||
[Tooltip("Trigger fired when a slide begins.")]
|
||||
[SerializeField] private string slideStarted = "SlideStarted";
|
||||
[Tooltip("Trigger fired when a slide ends.")]
|
||||
[SerializeField] private string slideEnded = "SlideEnded";
|
||||
[Tooltip("Trigger fired when a vault begins.")]
|
||||
[SerializeField] private string vaultStarted = "VaultStarted";
|
||||
[Tooltip("Trigger fired when a vault ends.")]
|
||||
[SerializeField] private string vaultEnded = "VaultEnded";
|
||||
[Tooltip("Trigger fired when an add-on module reports a mantle starting.")]
|
||||
[SerializeField] private string mantleStarted = "MantleStarted";
|
||||
[Tooltip("Trigger fired when an add-on module reports a mantle ending.")]
|
||||
[SerializeField] private string mantleEnded = "MantleEnded";
|
||||
|
||||
public string Speed => speed;
|
||||
public string PlanarSpeed => planarSpeed;
|
||||
public string NormalizedSpeed => normalizedSpeed;
|
||||
public string Forward => forward;
|
||||
public string Strafe => strafe;
|
||||
public string IsGrounded => isGrounded;
|
||||
public string IsFalling => isFalling;
|
||||
public string IsJumping => isJumping;
|
||||
public string IsSprinting => isSprinting;
|
||||
public string IsCrouching => isCrouching;
|
||||
public string IsProne => isProne;
|
||||
public string IsSliding => isSliding;
|
||||
public string Stance => stance;
|
||||
public string MovementState => movementState;
|
||||
public string JumpStarted => jumpStarted;
|
||||
public string Landed => landed;
|
||||
public string SlideStarted => slideStarted;
|
||||
public string SlideEnded => slideEnded;
|
||||
public string VaultStarted => vaultStarted;
|
||||
public string VaultEnded => vaultEnded;
|
||||
public string MantleStarted => mantleStarted;
|
||||
public string MantleEnded => mantleEnded;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 48eb654a49d14d5998664661cf5b635e
|
||||
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/Animation/CharacterAnimatorParameters.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f3906dc81be6740418b9d29689f3a89b
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,238 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
[RequireComponent(typeof(Camera))]
|
||||
/// <summary>
|
||||
/// A simple follow camera for testing the character controller and running the demo scene.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deliberately not a gameplay camera framework. Its only contract with the motor is calling
|
||||
/// <see cref="PlayerController.SetMainCameraTransform"/> so movement becomes camera-relative,
|
||||
/// which means any camera — your own, Cinemachine, or an add-on's — can replace it.
|
||||
/// </remarks>
|
||||
public class CameraFollow : MonoBehaviour
|
||||
{
|
||||
[Header("Target")]
|
||||
[SerializeField] private Transform target;
|
||||
[Tooltip("If Target is not assigned, search this component's scene for one PlayerController at startup. Assign Target explicitly for production, split-screen, additive scenes, or multiplayer.")]
|
||||
[SerializeField] private bool autoFindTargetInScene = true;
|
||||
[SerializeField] private Vector3 pivotOffset = new Vector3(0f, 1.4f, 0f);
|
||||
[Tooltip("Lateral camera offset in local space (positive X = over right shoulder).")]
|
||||
[SerializeField] private Vector3 shoulderOffset = new Vector3(0.35f, 0f, 0f);
|
||||
|
||||
[Header("Distance & Follow")]
|
||||
[Tooltip("How far the camera sits behind the pivot, in metres.")]
|
||||
[SerializeField, Min(0.1f)] private float distance = 5f;
|
||||
[Tooltip("How quickly the camera catches up to the target. Higher is tighter.")]
|
||||
[SerializeField, Min(1f)] private float followSpeed = 12f;
|
||||
|
||||
[Header("Look - Mouse")]
|
||||
[Tooltip("Degrees of rotation per unit of mouse delta.")]
|
||||
[SerializeField, Min(0f)] private float mouseSensitivity = 0.15f;
|
||||
[Tooltip("Caps mouse delta per frame so a hitch cannot whip the camera around.")]
|
||||
[SerializeField, Min(0f)] private float maxMouseDeltaPerFrame = 120f;
|
||||
|
||||
[Header("Look - Gamepad")]
|
||||
[Tooltip("Degrees per second at full stick deflection.")]
|
||||
[SerializeField, Min(0f)] private float gamepadSensitivity = 180f;
|
||||
[Tooltip("Stick movement below this is ignored.")]
|
||||
[SerializeField, Range(0f, 0.5f)] private float gamepadDeadzone = 0.15f;
|
||||
|
||||
[Header("Look - Clamp")]
|
||||
[Tooltip("Lowest pitch angle in degrees. Negative looks down at the character.")]
|
||||
[SerializeField] private float minPitch = -20f;
|
||||
[Tooltip("Highest pitch angle in degrees.")]
|
||||
[SerializeField] private float maxPitch = 60f;
|
||||
[Tooltip("Pitch the camera starts at.")]
|
||||
[SerializeField] private float initialPitch = 20f;
|
||||
[Tooltip("Inverts vertical look input.")]
|
||||
[SerializeField] private bool invertY;
|
||||
|
||||
[Header("Collision")]
|
||||
[SerializeField] private bool enableCollision = true;
|
||||
[SerializeField] private LayerMask collisionMask = ~0;
|
||||
[SerializeField, Min(0.05f)] private float collisionRadius = 0.3f;
|
||||
[Tooltip("How fast the camera retracts when blocked (units/sec).")]
|
||||
[SerializeField, Min(1f)] private float retractSpeed = 30f;
|
||||
[Tooltip("How fast the camera extends back out after a block clears (units/sec).")]
|
||||
[SerializeField, Min(0.1f)] private float extendSpeed = 4f;
|
||||
|
||||
[Header("Soft Lock-On")]
|
||||
[SerializeField] private bool enableLockOn = true;
|
||||
[Tooltip("0 = ignore the lock target, 1 = full yaw alignment toward target.")]
|
||||
[SerializeField, Range(0f, 1f)] private float lockOnInfluence = 0.65f;
|
||||
[SerializeField, Min(0.1f)] private float lockOnLerpSpeed = 6f;
|
||||
[Tooltip("Optional pitch bias when locked on (degrees).")]
|
||||
[SerializeField, Range(-30f, 30f)] private float lockOnPitchBias = 8f;
|
||||
|
||||
[Header("Auto Follow")]
|
||||
[Tooltip("Drift camera yaw behind the player when moving and the user is idle on look input.")]
|
||||
[SerializeField, Range(0f, 4f)] private float autoFollowYawSpeed = 1.2f;
|
||||
[Tooltip("Seconds after last look input before auto-follow kicks in.")]
|
||||
[SerializeField, Min(0f)] private float autoFollowIdleTime = 0.6f;
|
||||
|
||||
public Transform LockOnTarget { get; set; }
|
||||
|
||||
private Camera _camera;
|
||||
private float _yaw;
|
||||
private float _pitch;
|
||||
private float _currentDistance;
|
||||
private Vector3 _followVelocity;
|
||||
private float _idleTimer;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_camera = GetComponent<Camera>();
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
if (!target && autoFindTargetInScene)
|
||||
{
|
||||
PlayerController player = SceneReferenceResolver.FindComponentInSameScene<PlayerController>(this);
|
||||
if (player)
|
||||
target = player.transform;
|
||||
}
|
||||
|
||||
if (target && target.TryGetComponent(out PlayerController controller))
|
||||
controller.SetMainCameraTransform(transform);
|
||||
|
||||
Vector3 euler = transform.eulerAngles;
|
||||
_yaw = euler.y;
|
||||
_pitch = initialPitch;
|
||||
_currentDistance = distance;
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (!target)
|
||||
return;
|
||||
|
||||
Vector2 lookDelta = ReadLookInput(out bool gamepadActive);
|
||||
ApplyLook(lookDelta, gamepadActive);
|
||||
ApplyAutoFollow(lookDelta.sqrMagnitude);
|
||||
ApplyLockOn();
|
||||
|
||||
Quaternion rotation = Quaternion.Euler(_pitch, _yaw, 0f);
|
||||
Vector3 pivot = target.position + pivotOffset;
|
||||
Vector3 lateral = rotation * shoulderOffset;
|
||||
|
||||
Vector3 cameraDirection = -(rotation * Vector3.forward);
|
||||
float targetDistance = ResolveCollisionDistance(pivot + lateral, cameraDirection);
|
||||
|
||||
if (targetDistance < _currentDistance)
|
||||
_currentDistance = Mathf.MoveTowards(_currentDistance, targetDistance, retractSpeed * Time.deltaTime);
|
||||
else
|
||||
_currentDistance = Mathf.MoveTowards(_currentDistance, targetDistance, extendSpeed * Time.deltaTime);
|
||||
|
||||
Vector3 desiredPosition = pivot + lateral + cameraDirection * _currentDistance;
|
||||
|
||||
Vector3 smoothedPosition = Vector3.SmoothDamp(
|
||||
transform.position,
|
||||
desiredPosition,
|
||||
ref _followVelocity,
|
||||
1f / followSpeed);
|
||||
|
||||
transform.SetPositionAndRotation(smoothedPosition, rotation);
|
||||
}
|
||||
|
||||
private Vector2 ReadLookInput(out bool gamepadActive)
|
||||
{
|
||||
gamepadActive = false;
|
||||
Vector2 result = Vector2.zero;
|
||||
|
||||
Mouse mouse = Mouse.current;
|
||||
if (mouse != null)
|
||||
{
|
||||
Vector2 mouseDelta = mouse.delta.ReadValue();
|
||||
if (maxMouseDeltaPerFrame > 0f)
|
||||
mouseDelta = Vector2.ClampMagnitude(mouseDelta, maxMouseDeltaPerFrame);
|
||||
result = mouseDelta * mouseSensitivity;
|
||||
}
|
||||
|
||||
Gamepad gamepad = Gamepad.current;
|
||||
if (gamepad != null)
|
||||
{
|
||||
Vector2 stick = gamepad.rightStick.ReadValue();
|
||||
if (stick.sqrMagnitude > gamepadDeadzone * gamepadDeadzone)
|
||||
{
|
||||
Vector2 stickDelta = stick * (gamepadSensitivity * Time.deltaTime);
|
||||
if (stickDelta.sqrMagnitude > result.sqrMagnitude)
|
||||
{
|
||||
result = stickDelta;
|
||||
gamepadActive = true;
|
||||
}
|
||||
else if (result.sqrMagnitude < 0.001f)
|
||||
{
|
||||
result = stickDelta;
|
||||
gamepadActive = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void ApplyLook(Vector2 lookDelta, bool gamepadActive)
|
||||
{
|
||||
float yawDelta = lookDelta.x;
|
||||
float pitchDelta = invertY ? lookDelta.y : -lookDelta.y;
|
||||
|
||||
_yaw += yawDelta;
|
||||
_pitch = Mathf.Clamp(_pitch + pitchDelta, minPitch, maxPitch);
|
||||
|
||||
_idleTimer = lookDelta.sqrMagnitude > 0.0001f ? 0f : _idleTimer + Time.deltaTime;
|
||||
}
|
||||
|
||||
private void ApplyAutoFollow(float lookDeltaSqr)
|
||||
{
|
||||
if (autoFollowYawSpeed <= 0f)
|
||||
return;
|
||||
|
||||
if (_idleTimer < autoFollowIdleTime)
|
||||
return;
|
||||
|
||||
if (!target.TryGetComponent(out PlayerController controller) || controller.RigidBody == null)
|
||||
return;
|
||||
|
||||
Vector3 velocity = controller.RigidBody.linearVelocity;
|
||||
velocity.y = 0f;
|
||||
if (velocity.sqrMagnitude < 0.5f)
|
||||
return;
|
||||
|
||||
float targetYaw = Mathf.Atan2(velocity.x, velocity.z) * Mathf.Rad2Deg;
|
||||
_yaw = Mathf.LerpAngle(_yaw, targetYaw, autoFollowYawSpeed * Time.deltaTime);
|
||||
}
|
||||
|
||||
private void ApplyLockOn()
|
||||
{
|
||||
if (!enableLockOn || lockOnInfluence <= 0f || LockOnTarget == null)
|
||||
return;
|
||||
|
||||
Vector3 toTarget = LockOnTarget.position - (target.position + pivotOffset);
|
||||
toTarget.y = 0f;
|
||||
if (toTarget.sqrMagnitude < 0.0001f)
|
||||
return;
|
||||
|
||||
float yawToTarget = Mathf.Atan2(toTarget.x, toTarget.z) * Mathf.Rad2Deg;
|
||||
float blend = lockOnInfluence * lockOnLerpSpeed * Time.deltaTime;
|
||||
_yaw = Mathf.LerpAngle(_yaw, yawToTarget, blend);
|
||||
|
||||
if (Mathf.Abs(lockOnPitchBias) > 0.01f)
|
||||
_pitch = Mathf.LerpAngle(_pitch, lockOnPitchBias, blend);
|
||||
}
|
||||
|
||||
private float ResolveCollisionDistance(Vector3 castOrigin, Vector3 castDirection)
|
||||
{
|
||||
if (!enableCollision)
|
||||
return distance;
|
||||
|
||||
if (Physics.SphereCast(castOrigin, collisionRadius, castDirection, out RaycastHit hit, distance, collisionMask, QueryTriggerInteraction.Ignore))
|
||||
return Mathf.Max(hit.distance, collisionRadius);
|
||||
|
||||
return distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0a01ac3d63e1c814695b6ae5d9680448
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Camera/CameraFollow.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,238 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
[AddComponentMenu("Character Controller/Camera/Cinemachine Adapter")]
|
||||
public sealed class CharacterCinemachineAdapter : MonoBehaviour
|
||||
{
|
||||
[Header("References")]
|
||||
[Tooltip("Controller the rig follows. Found automatically when Auto Find Player is on.")]
|
||||
[SerializeField] private PlayerController playerController;
|
||||
[Tooltip("Your Cinemachine camera component. Stored as a plain Component so Core compiles without "
|
||||
+ "Cinemachine installed.")]
|
||||
[SerializeField] private Component cinemachineCamera;
|
||||
[Tooltip("Transform the Cinemachine camera follows.")]
|
||||
[SerializeField] private Transform followTarget;
|
||||
[Tooltip("Transform the Cinemachine camera looks at.")]
|
||||
[SerializeField] private Transform lookAtTarget;
|
||||
|
||||
[Header("Setup")]
|
||||
[Tooltip("Searches this scene for a PlayerController when none is assigned.")]
|
||||
[SerializeField] private bool autoFindPlayer = true;
|
||||
[Tooltip("Searches this GameObject and its children for a Cinemachine camera.")]
|
||||
[SerializeField] private bool autoFindCinemachineCamera = true;
|
||||
[Tooltip("Writes the follow target onto the Cinemachine camera at startup.")]
|
||||
[SerializeField] private bool assignFollowTarget = true;
|
||||
[Tooltip("Writes the look-at target onto the Cinemachine camera at startup.")]
|
||||
[SerializeField] private bool assignLookAtTarget = true;
|
||||
[Tooltip("Tells the controller to treat this camera as the movement reference, so input stays "
|
||||
+ "camera-relative. Keep this on.")]
|
||||
[SerializeField] private bool assignPlayerCameraReference = true;
|
||||
[Tooltip("How often to re-assign the camera reference, in seconds, in case the Cinemachine brain "
|
||||
+ "swaps cameras.")]
|
||||
[SerializeField, Min(0f)] private float cameraReferenceRefreshInterval = 0.25f;
|
||||
|
||||
private Camera _cachedMainCamera;
|
||||
private Transform _lastAssignedCameraTransform;
|
||||
private float _nextCameraReferenceRefreshTime;
|
||||
|
||||
public PlayerController PlayerController => playerController;
|
||||
public Component CinemachineCamera => cinemachineCamera;
|
||||
|
||||
public bool ValidateTargetBindings(out string message)
|
||||
{
|
||||
Component resolvedCamera = cinemachineCamera ? cinemachineCamera : autoFindCinemachineCamera ? FindCinemachineComponent() : null;
|
||||
if (!resolvedCamera)
|
||||
{
|
||||
message = "No Cinemachine camera component is assigned or discoverable on this adapter GameObject.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (assignFollowTarget && !CanSetTransformMember(resolvedCamera, "Follow", "m_Follow"))
|
||||
{
|
||||
message = $"'{resolvedCamera.GetType().Name}' does not expose a writable Follow target member supported by the adapter.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (assignLookAtTarget && !CanSetTransformMember(resolvedCamera, "LookAt", "m_LookAt"))
|
||||
{
|
||||
message = $"'{resolvedCamera.GetType().Name}' does not expose a writable LookAt target member supported by the adapter.";
|
||||
return false;
|
||||
}
|
||||
|
||||
message = "Cinemachine target bindings are supported.";
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
ResolveReferences();
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
ResolveReferences();
|
||||
ApplyTargets();
|
||||
ApplyPlayerCameraReference();
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (cameraReferenceRefreshInterval > 0f
|
||||
&& Time.unscaledTime < _nextCameraReferenceRefreshTime
|
||||
&& _lastAssignedCameraTransform)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ApplyPlayerCameraReference();
|
||||
}
|
||||
|
||||
public bool ApplyTargets()
|
||||
{
|
||||
if (!cinemachineCamera)
|
||||
return false;
|
||||
|
||||
Transform resolvedFollow = followTarget ? followTarget : playerController ? playerController.transform : null;
|
||||
Transform resolvedLookAt = lookAtTarget ? lookAtTarget : resolvedFollow;
|
||||
bool changed = false;
|
||||
|
||||
if (assignFollowTarget && resolvedFollow)
|
||||
changed |= TrySetTransformMember(cinemachineCamera, "Follow", "m_Follow", resolvedFollow);
|
||||
|
||||
if (assignLookAtTarget && resolvedLookAt)
|
||||
changed |= TrySetTransformMember(cinemachineCamera, "LookAt", "m_LookAt", resolvedLookAt);
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
private void ResolveReferences()
|
||||
{
|
||||
if (!playerController && autoFindPlayer)
|
||||
playerController = GetComponentInParent<PlayerController>() ?? SceneReferenceResolver.FindComponentInSameScene<PlayerController>(this);
|
||||
|
||||
if (!followTarget && playerController)
|
||||
followTarget = playerController.transform;
|
||||
|
||||
if (!lookAtTarget)
|
||||
lookAtTarget = followTarget;
|
||||
|
||||
if (!cinemachineCamera && autoFindCinemachineCamera)
|
||||
cinemachineCamera = FindCinemachineComponent();
|
||||
}
|
||||
|
||||
private void ApplyPlayerCameraReference()
|
||||
{
|
||||
if (!assignPlayerCameraReference || !playerController)
|
||||
return;
|
||||
|
||||
_nextCameraReferenceRefreshTime = Time.unscaledTime + cameraReferenceRefreshInterval;
|
||||
Camera mainCamera = ResolveMainCamera();
|
||||
if (!mainCamera)
|
||||
return;
|
||||
|
||||
Transform cameraTransform = mainCamera.transform;
|
||||
if (_lastAssignedCameraTransform == cameraTransform)
|
||||
return;
|
||||
|
||||
playerController.SetMainCameraTransform(cameraTransform);
|
||||
_lastAssignedCameraTransform = cameraTransform;
|
||||
}
|
||||
|
||||
private Camera ResolveMainCamera()
|
||||
{
|
||||
if (_cachedMainCamera)
|
||||
return _cachedMainCamera;
|
||||
|
||||
_cachedMainCamera = SceneReferenceResolver.FindMainCameraInSameScene(this);
|
||||
return _cachedMainCamera;
|
||||
}
|
||||
|
||||
private Component FindCinemachineComponent()
|
||||
{
|
||||
Component[] components = GetComponents<Component>();
|
||||
foreach (Component component in components)
|
||||
{
|
||||
if (component != this && IsCinemachineComponent(component))
|
||||
return component;
|
||||
}
|
||||
|
||||
Component[] children = GetComponentsInChildren<Component>(true);
|
||||
foreach (Component component in children)
|
||||
{
|
||||
if (component != this && IsCinemachineComponent(component))
|
||||
return component;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsCinemachineComponent(Component component)
|
||||
{
|
||||
if (!component)
|
||||
return false;
|
||||
|
||||
Type type = component.GetType();
|
||||
string fullName = type.FullName ?? string.Empty;
|
||||
return fullName.StartsWith("Cinemachine.", StringComparison.Ordinal)
|
||||
|| type.Name.IndexOf("Cinemachine", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
}
|
||||
|
||||
private static bool TrySetTransformMember(Component component, string propertyName, string fieldName, Transform value)
|
||||
{
|
||||
if (TryGetWritableTransformProperty(component, propertyName, out PropertyInfo property))
|
||||
{
|
||||
if (property.GetValue(component) as Transform == value)
|
||||
return false;
|
||||
|
||||
property.SetValue(component, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TryGetWritableTransformField(component, fieldName, propertyName, out FieldInfo field))
|
||||
{
|
||||
if (field.GetValue(component) as Transform == value)
|
||||
return false;
|
||||
|
||||
field.SetValue(component, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool CanSetTransformMember(Component component, string propertyName, string fieldName)
|
||||
{
|
||||
return TryGetWritableTransformProperty(component, propertyName, out _)
|
||||
|| TryGetWritableTransformField(component, fieldName, propertyName, out _);
|
||||
}
|
||||
|
||||
private static bool TryGetWritableTransformProperty(Component component, string propertyName, out PropertyInfo property)
|
||||
{
|
||||
property = null;
|
||||
if (!component)
|
||||
return false;
|
||||
|
||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
||||
property = component.GetType().GetProperty(propertyName, flags);
|
||||
return property != null
|
||||
&& property.CanWrite
|
||||
&& property.PropertyType.IsAssignableFrom(typeof(Transform));
|
||||
}
|
||||
|
||||
private static bool TryGetWritableTransformField(Component component, string fieldName, string fallbackFieldName, out FieldInfo field)
|
||||
{
|
||||
field = null;
|
||||
if (!component)
|
||||
return false;
|
||||
|
||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
||||
Type type = component.GetType();
|
||||
field = type.GetField(fieldName, flags) ?? type.GetField(fallbackFieldName, flags);
|
||||
return field != null
|
||||
&& field.FieldType.IsAssignableFrom(typeof(Transform));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 172c34e7d0ec406fa55c4acd42efde70
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Camera/CharacterCinemachineAdapter.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 103d3495bf4843509d5f5ad87bc3b952
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,106 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
/// <summary>
|
||||
/// Toggles the demo HUD and the controller's debug overlay. Demo helper; not part of the
|
||||
/// character motor.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Character Controller/Core/Demo HUD Toggle")]
|
||||
public sealed class DemoHudToggle : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Controller the rig follows. Found automatically when Auto Find Player is on.")]
|
||||
[SerializeField] private PlayerController playerController;
|
||||
[Tooltip("Canvas shown and hidden by the toggle key. Found by name if left empty.")]
|
||||
[SerializeField] private Canvas hudCanvas;
|
||||
[Tooltip("Key that shows and hides the demo HUD and the controller's debug overlay.")]
|
||||
[SerializeField] private KeyCode toggleKey = KeyCode.F1;
|
||||
[Tooltip("Whether the HUD starts visible.")]
|
||||
[SerializeField] private bool visible = true;
|
||||
|
||||
private GUIStyle _hintStyle;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
ResolveReferences();
|
||||
ApplyVisibility();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!InputSystemKeyCodeUtility.WasPressedThisFrame(toggleKey))
|
||||
return;
|
||||
|
||||
visible = !visible;
|
||||
ApplyVisibility();
|
||||
}
|
||||
|
||||
private void OnGUI()
|
||||
{
|
||||
if (!visible)
|
||||
return;
|
||||
|
||||
EnsureHintStyle();
|
||||
const float width = 210f;
|
||||
const float height = 32f;
|
||||
GUI.Box(
|
||||
new Rect(Screen.width - width - 16f, Screen.height - height - 16f, width, height),
|
||||
"F1 - Hide HUD / debug",
|
||||
_hintStyle);
|
||||
}
|
||||
|
||||
private void ResolveReferences()
|
||||
{
|
||||
if (!playerController)
|
||||
playerController = GetComponent<PlayerController>() ?? SceneReferenceResolver.FindComponentInSameScene<PlayerController>(this);
|
||||
|
||||
if (!hudCanvas)
|
||||
hudCanvas = FindNamedCanvas("HUD_Canvas");
|
||||
}
|
||||
|
||||
private Canvas FindNamedCanvas(string canvasName)
|
||||
{
|
||||
if (!gameObject.scene.IsValid() || !gameObject.scene.isLoaded)
|
||||
return null;
|
||||
|
||||
GameObject[] roots = gameObject.scene.GetRootGameObjects();
|
||||
for (int i = 0; i < roots.Length; i++)
|
||||
{
|
||||
Canvas[] canvases = roots[i].GetComponentsInChildren<Canvas>(true);
|
||||
for (int j = 0; j < canvases.Length; j++)
|
||||
{
|
||||
if (canvases[j] && canvases[j].name == canvasName)
|
||||
return canvases[j];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void ApplyVisibility()
|
||||
{
|
||||
if (!playerController || !hudCanvas)
|
||||
ResolveReferences();
|
||||
|
||||
if (playerController)
|
||||
playerController.SetDebugOverlayVisible(visible);
|
||||
|
||||
if (hudCanvas)
|
||||
hudCanvas.enabled = visible;
|
||||
}
|
||||
|
||||
private void EnsureHintStyle()
|
||||
{
|
||||
if (_hintStyle != null)
|
||||
return;
|
||||
|
||||
_hintStyle = new GUIStyle(GUI.skin.box)
|
||||
{
|
||||
alignment = TextAnchor.MiddleCenter,
|
||||
fontSize = 13,
|
||||
normal = { textColor = Color.white },
|
||||
padding = new RectOffset(8, 8, 6, 6)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a58c00ec2dc0495e9d82ee1573a5590a
|
||||
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/Demo/DemoHudToggle.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,49 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
/// <summary>
|
||||
/// Ping-pongs a platform between two points. Demo helper used by the generated movement gym;
|
||||
/// it is not part of the character motor.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Character Controller/Core/Demo Moving Platform Mover")]
|
||||
public sealed class DemoMovingPlatformMover : MonoBehaviour
|
||||
{
|
||||
[Tooltip("Offset from the starting position the platform travels to, in local space.")]
|
||||
[SerializeField] private Vector3 localOffset = new Vector3(0f, 0f, 3f);
|
||||
[Tooltip("Seconds for one leg of the round trip.")]
|
||||
[SerializeField, Min(0.1f)] private float duration = 2.5f;
|
||||
|
||||
private Vector3 _startPosition;
|
||||
private Rigidbody _rigidbody;
|
||||
|
||||
public Vector3 LocalOffset
|
||||
{
|
||||
get => localOffset;
|
||||
set => localOffset = value;
|
||||
}
|
||||
|
||||
public float Duration
|
||||
{
|
||||
get => duration;
|
||||
set => duration = Mathf.Max(0.1f, value);
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
_startPosition = transform.position;
|
||||
_rigidbody = GetComponent<Rigidbody>();
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
float phase = Mathf.PingPong(Time.time / duration, 1f);
|
||||
Vector3 target = _startPosition + transform.TransformDirection(localOffset) * phase;
|
||||
|
||||
if (_rigidbody && _rigidbody.isKinematic)
|
||||
_rigidbody.MovePosition(target);
|
||||
else
|
||||
transform.position = target;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b453ced1145f4db9b69f47cb743de015
|
||||
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/Demo/DemoMovingPlatformMover.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2e5ae8265c374254f975ada5d9a3b321
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,290 @@
|
||||
{
|
||||
"version": 1,
|
||||
"name": "Controls",
|
||||
"maps": [
|
||||
{
|
||||
"name": "Control",
|
||||
"id": "55a13aec-5a6d-4b4c-bb6a-90718753e458",
|
||||
"actions": [
|
||||
{
|
||||
"name": "Move",
|
||||
"type": "Value",
|
||||
"id": "07044d6a-8693-4677-b81e-65664ca92bf9",
|
||||
"expectedControlType": "Vector2",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": true
|
||||
},
|
||||
{
|
||||
"name": "Look",
|
||||
"type": "Value",
|
||||
"id": "c4a37b2b-f58e-4bed-bad7-b9b5233fc94f",
|
||||
"expectedControlType": "Vector2",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": true
|
||||
},
|
||||
{
|
||||
"name": "Jump",
|
||||
"type": "Button",
|
||||
"id": "4b64d549-fdcd-4bb9-8dfa-9a6e619309b9",
|
||||
"expectedControlType": "Button",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false
|
||||
},
|
||||
{
|
||||
"name": "Crouch",
|
||||
"type": "Button",
|
||||
"id": "28cc9761-81ca-495b-a15a-20944b18d14b",
|
||||
"expectedControlType": "Button",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false
|
||||
},
|
||||
{
|
||||
"name": "Dash",
|
||||
"type": "Button",
|
||||
"id": "e5bc0705-bbf1-49a5-9dfb-acd0f513a635",
|
||||
"expectedControlType": "",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false
|
||||
},
|
||||
{
|
||||
"name": "Walk",
|
||||
"type": "Button",
|
||||
"id": "4274c722-fc7a-4609-8cf7-03c31c001825",
|
||||
"expectedControlType": "Button",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false
|
||||
},
|
||||
{
|
||||
"name": "Sprint",
|
||||
"type": "Button",
|
||||
"id": "866d7580-8041-4c95-927c-940e7bbc1ea8",
|
||||
"expectedControlType": "Button",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false
|
||||
},
|
||||
{
|
||||
"name": "Prone",
|
||||
"type": "Button",
|
||||
"id": "451e2596-de3a-453e-a751-3eb2f4ae07b9",
|
||||
"expectedControlType": "Button",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false
|
||||
}
|
||||
],
|
||||
"bindings": [
|
||||
{
|
||||
"name": "2D Vector",
|
||||
"id": "845d4d91-41e0-4345-aa9e-98cc0b8af61a",
|
||||
"path": "2DVector",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": true,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "up",
|
||||
"id": "9f529ebc-378b-44db-9977-60b2b4281eeb",
|
||||
"path": "<Keyboard>/w",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "down",
|
||||
"id": "5a72236d-4580-4a5b-9400-3ec5c41b9c7c",
|
||||
"path": "<Keyboard>/s",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "left",
|
||||
"id": "fc6ecc3f-7d0e-4c08-8c3e-4cad523c3bfd",
|
||||
"path": "<Keyboard>/a",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "right",
|
||||
"id": "2ed21813-ed53-4f7d-8025-80e5d764fe1b",
|
||||
"path": "<Keyboard>/d",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "up",
|
||||
"id": "352bac99-3185-463f-8879-2c95737e69c7",
|
||||
"path": "<Keyboard>/upArrow",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "down",
|
||||
"id": "61ffb665-6f37-4256-868a-926b41477af0",
|
||||
"path": "<Keyboard>/downArrow",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "left",
|
||||
"id": "d50c7c2f-d5a9-4029-9790-83a42d023aa3",
|
||||
"path": "<Keyboard>/leftArrow",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "right",
|
||||
"id": "e42c406b-d211-4420-98ff-6fe5dfb3624e",
|
||||
"path": "<Keyboard>/rightArrow",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Move",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": true
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "280a58c7-f0a0-4f79-a5ff-09974f3a5355",
|
||||
"path": "<Keyboard>/space",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Jump",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "32270217-c493-45d1-8f18-6d7e8d0fb7f3",
|
||||
"path": "<Keyboard>/ctrl",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Crouch",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "ced9c90c-08df-4b20-ba32-f4c686b44ccf",
|
||||
"path": "<Keyboard>/alt",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Walk",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "5c805672-37b0-4261-9c70-26362812f512",
|
||||
"path": "<Pointer>/delta",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Look",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "0f99c2bc-e04b-4a63-b080-d763509c083e",
|
||||
"path": "<Keyboard>/shift",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Sprint",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "bad6d415-4fa0-44cb-9a06-539092539fd3",
|
||||
"path": "<Keyboard>/e",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Dash",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "fbd3ef64-32ce-49e9-bbe8-55347f75254e",
|
||||
"path": "<Keyboard>/z",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Prone",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"controlSchemes": [
|
||||
{
|
||||
"name": "New control scheme",
|
||||
"bindingGroup": "New control scheme",
|
||||
"devices": [
|
||||
{
|
||||
"devicePath": "<Keyboard>",
|
||||
"isOptional": false,
|
||||
"isOR": false
|
||||
},
|
||||
{
|
||||
"devicePath": "<Gamepad>",
|
||||
"isOptional": false,
|
||||
"isOR": false
|
||||
},
|
||||
{
|
||||
"devicePath": "<Joystick>",
|
||||
"isOptional": false,
|
||||
"isOR": false
|
||||
},
|
||||
{
|
||||
"devicePath": "<Mouse>",
|
||||
"isOptional": false,
|
||||
"isOR": false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6da0542b9a9ab794f861de14633db34c
|
||||
ScriptedImporter:
|
||||
internalIDToNameTable: []
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
script: {fileID: 11500000, guid: 8404be70184654265930450def6a9037, type: 3}
|
||||
generateWrapperCode: 0
|
||||
wrapperCodePath:
|
||||
wrapperClassName:
|
||||
wrapperCodeNamespace: CharacterMovement
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Input/Controls.inputactions
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
/// <summary>
|
||||
/// Everything the character motor needs to know about player intent.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Locomotion reads intent through this interface and never touches key bindings or the Input
|
||||
/// System directly, so a project can drive the same controller from an AI brain, a replay, a
|
||||
/// network stream, or its own input stack by supplying a different implementation to
|
||||
/// <see cref="PlayerController.SetInputSource"/>.
|
||||
/// <para>
|
||||
/// The shipped implementation is <see cref="InputHandler"/>, which binds these values to a Unity
|
||||
/// Input System action map.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// // Driving the controller from code instead of from a device.
|
||||
/// public sealed class ScriptedInput : MonoBehaviour, ICharacterInputSource
|
||||
/// {
|
||||
/// public Vector2 MoveDirection { get; set; }
|
||||
/// public bool IsMoving => MoveDirection.sqrMagnitude > 0.0001f;
|
||||
/// public bool IsSprinting { get; set; }
|
||||
/// public bool IsWalking => false;
|
||||
/// public bool IsCrouching { get; set; }
|
||||
/// public bool IsProne => false;
|
||||
///
|
||||
/// public event Action JumpPerformed;
|
||||
/// public event Action DashPerformed;
|
||||
/// public event Action CrouchPerformed;
|
||||
/// public event Action PronePerformed;
|
||||
///
|
||||
/// public void Jump() => JumpPerformed?.Invoke();
|
||||
/// }
|
||||
/// </code>
|
||||
/// </example>
|
||||
public interface ICharacterInputSource
|
||||
{
|
||||
/// <summary>Planar movement intent, where y is forward. Magnitudes above 1 are clamped.</summary>
|
||||
Vector2 MoveDirection { get; }
|
||||
|
||||
/// <summary>True while <see cref="MoveDirection"/> is non-zero.</summary>
|
||||
bool IsMoving { get; }
|
||||
|
||||
/// <summary>True while the sprint modifier is held.</summary>
|
||||
bool IsSprinting { get; }
|
||||
|
||||
/// <summary>True while the walk modifier is held.</summary>
|
||||
bool IsWalking { get; }
|
||||
|
||||
/// <summary>True while the crouch input is held.</summary>
|
||||
bool IsCrouching { get; }
|
||||
|
||||
/// <summary>True while prone is toggled on.</summary>
|
||||
bool IsProne { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True while the jump input is held down. Drives variable jump height; an implementation
|
||||
/// that only pulses <see cref="JumpPerformed"/> can return false and jumps stay full height.
|
||||
/// </summary>
|
||||
bool IsJumpHeld { get; }
|
||||
|
||||
/// <summary>Raised once when the jump input is pressed.</summary>
|
||||
event Action JumpPerformed;
|
||||
|
||||
/// <summary>Raised once when the dash input is pressed.</summary>
|
||||
event Action DashPerformed;
|
||||
|
||||
/// <summary>Raised once when the crouch input is pressed.</summary>
|
||||
event Action CrouchPerformed;
|
||||
|
||||
/// <summary>Raised once when the prone input is pressed.</summary>
|
||||
event Action PronePerformed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6637cbbb64914e32be1abbc4852424c0
|
||||
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/Input/ICharacterInputSource.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,67 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
public abstract class InputExtensionModule : MonoBehaviour
|
||||
{
|
||||
protected InputActionAsset[] InputAssets { get; private set; }
|
||||
|
||||
internal void EnableActions(InputActionAsset[] assets)
|
||||
{
|
||||
InputAssets = assets;
|
||||
OnActionsEnabled();
|
||||
}
|
||||
|
||||
internal void DisableActions()
|
||||
{
|
||||
OnActionsDisabled();
|
||||
}
|
||||
|
||||
internal void Suspend()
|
||||
{
|
||||
OnActionsSuspended();
|
||||
}
|
||||
|
||||
internal void Resume()
|
||||
{
|
||||
OnActionsResumed();
|
||||
}
|
||||
|
||||
protected InputActionMap FindMap(string mapName)
|
||||
{
|
||||
if (InputAssets == null)
|
||||
return null;
|
||||
|
||||
InputActionMap firstMatch = null;
|
||||
int matchCount = 0;
|
||||
|
||||
foreach (InputActionAsset asset in InputAssets)
|
||||
{
|
||||
InputActionMap map = asset?.FindActionMap(mapName, throwIfNotFound: false);
|
||||
if (map == null)
|
||||
continue;
|
||||
|
||||
matchCount++;
|
||||
if (firstMatch == null)
|
||||
{
|
||||
firstMatch = map;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (matchCount == 2)
|
||||
Debug.LogWarning($"[{GetType().Name}] Multiple action maps named '{mapName}' were found. Using the first match.");
|
||||
}
|
||||
|
||||
if (firstMatch == null)
|
||||
Debug.LogWarning($"[{GetType().Name}] Action map '{mapName}' not found.");
|
||||
|
||||
return firstMatch;
|
||||
}
|
||||
|
||||
protected abstract void OnActionsEnabled();
|
||||
protected abstract void OnActionsDisabled();
|
||||
protected virtual void OnActionsSuspended() { }
|
||||
protected virtual void OnActionsResumed() { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 27804f1084fd8fc449e2a6394afcd402
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Input/InputExtensionModule.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,364 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
using UnityEngine.Serialization;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
/// <summary>
|
||||
/// Binds Unity Input System actions to the character motor's <see cref="ICharacterInputSource"/>
|
||||
/// contract. Replaceable: see <see cref="PlayerController.SetInputSource"/>.
|
||||
/// </summary>
|
||||
public class InputHandler : MonoBehaviour, ICharacterInputSource
|
||||
{
|
||||
[FormerlySerializedAs("_coreAsset")]
|
||||
[Tooltip("Input Action asset holding the movement action map.")]
|
||||
[SerializeField] private InputActionAsset movementActionsAsset;
|
||||
|
||||
[FormerlySerializedAs("_coreMapName")]
|
||||
[Tooltip("Name of the action map inside the asset that holds the movement actions. Must match "
|
||||
+ "exactly.")]
|
||||
[SerializeField] private string movementActionMapName = "Control";
|
||||
|
||||
[FormerlySerializedAs("_extraAssets")]
|
||||
[SerializeField]
|
||||
[Tooltip("Extra action assets made available to InputExtensionModule components, such as the "
|
||||
+ "FPS add-on's weapon actions.")]
|
||||
private InputActionAsset[] extensionActionAssets = Array.Empty<InputActionAsset>();
|
||||
|
||||
[Header("Action Names")]
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the 2D movement action in the map above. Required.")]
|
||||
private string moveActionName = "Move";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the jump button action. Clear the field to disable jumping input.")]
|
||||
private string jumpActionName = "Jump";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the sprint modifier action. Clear the field to disable sprinting input.")]
|
||||
private string sprintActionName = "Sprint";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the walk modifier action. Clear the field to disable walking input.")]
|
||||
private string walkActionName = "Walk";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the crouch action. Clear the field to disable crouching input.")]
|
||||
private string crouchActionName = "Crouch";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the prone toggle action. Clear the field to disable prone input.")]
|
||||
private string proneActionName = "Prone";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Name of the dash action. Clear the field to disable dashing input.")]
|
||||
private string dashActionName = "Dash";
|
||||
|
||||
[SerializeField]
|
||||
[Tooltip("Logs a warning when a named action is missing from the map. Turn off if you "
|
||||
+ "deliberately ship maps without some of these actions.")]
|
||||
private bool warnOnMissingActions = true;
|
||||
|
||||
public InputActionAsset CoreAsset => movementActionsAsset;
|
||||
public InputActionAsset[] AllAssets { get; private set; }
|
||||
|
||||
public Vector2 MoveDirection { get; private set; }
|
||||
public bool IsCrouching { get; private set; }
|
||||
public bool IsProne { get; private set; }
|
||||
public bool IsSprinting { get; private set; }
|
||||
public bool IsWalking { get; private set; }
|
||||
public bool IsMoving { get; private set; }
|
||||
public bool IsJumpHeld { get; private set; }
|
||||
|
||||
public event Action JumpEvent;
|
||||
public event Action DashEvent;
|
||||
public event Action CrouchEvent;
|
||||
public event Action ProneEvent;
|
||||
|
||||
// The interface names are the stable contract; the *Event names above are kept so existing
|
||||
// projects that subscribe to them keep compiling.
|
||||
event Action ICharacterInputSource.JumpPerformed
|
||||
{
|
||||
add => JumpEvent += value;
|
||||
remove => JumpEvent -= value;
|
||||
}
|
||||
|
||||
event Action ICharacterInputSource.DashPerformed
|
||||
{
|
||||
add => DashEvent += value;
|
||||
remove => DashEvent -= value;
|
||||
}
|
||||
|
||||
event Action ICharacterInputSource.CrouchPerformed
|
||||
{
|
||||
add => CrouchEvent += value;
|
||||
remove => CrouchEvent -= value;
|
||||
}
|
||||
|
||||
event Action ICharacterInputSource.PronePerformed
|
||||
{
|
||||
add => ProneEvent += value;
|
||||
remove => ProneEvent -= value;
|
||||
}
|
||||
|
||||
private InputActionMap _movementActionMap;
|
||||
private InputExtensionModule[] _extensionModules;
|
||||
|
||||
private readonly Dictionary<InputAction, List<Action<InputAction.CallbackContext>>> _callbackRegistry =
|
||||
new Dictionary<InputAction, List<Action<InputAction.CallbackContext>>>();
|
||||
|
||||
private readonly Stack<InputMode> _inputModeStack = new Stack<InputMode>();
|
||||
|
||||
private void Start()
|
||||
{
|
||||
if (!movementActionsAsset)
|
||||
{
|
||||
Debug.LogError("[InputHandler] Movement action asset is not assigned.");
|
||||
return;
|
||||
}
|
||||
|
||||
List<InputActionAsset> allAssets = new List<InputActionAsset> { movementActionsAsset };
|
||||
if (extensionActionAssets != null)
|
||||
{
|
||||
foreach (InputActionAsset asset in extensionActionAssets)
|
||||
{
|
||||
if (asset != null)
|
||||
allAssets.Add(asset);
|
||||
}
|
||||
}
|
||||
|
||||
AllAssets = allAssets.ToArray();
|
||||
|
||||
_movementActionMap = movementActionsAsset.FindActionMap(movementActionMapName, throwIfNotFound: false);
|
||||
if (_movementActionMap == null)
|
||||
{
|
||||
Debug.LogError($"[InputHandler] Action map '{movementActionMapName}' not found in '{movementActionsAsset.name}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
RegisterActionCallbacks();
|
||||
_movementActionMap.Enable();
|
||||
|
||||
_extensionModules = GetComponents<InputExtensionModule>();
|
||||
foreach (InputExtensionModule module in _extensionModules)
|
||||
module.EnableActions(AllAssets);
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
foreach (KeyValuePair<InputAction, List<Action<InputAction.CallbackContext>>> entry in _callbackRegistry)
|
||||
{
|
||||
InputAction action = entry.Key;
|
||||
foreach (Action<InputAction.CallbackContext> callback in entry.Value)
|
||||
{
|
||||
action.started -= callback;
|
||||
action.performed -= callback;
|
||||
action.canceled -= callback;
|
||||
}
|
||||
}
|
||||
|
||||
_movementActionMap?.Disable();
|
||||
ResetMovementState();
|
||||
|
||||
if (_extensionModules == null)
|
||||
return;
|
||||
|
||||
foreach (InputExtensionModule module in _extensionModules)
|
||||
module.DisableActions();
|
||||
}
|
||||
|
||||
public void PushInputMode(InputMode mode)
|
||||
{
|
||||
if (mode == null)
|
||||
return;
|
||||
|
||||
if (_inputModeStack.Count == 0)
|
||||
SuspendExtensions();
|
||||
|
||||
_inputModeStack.Push(mode);
|
||||
mode.Activate(AllAssets ?? Array.Empty<InputActionAsset>());
|
||||
SyncCoreMovementSuspension();
|
||||
}
|
||||
|
||||
public void PopInputMode(InputMode mode)
|
||||
{
|
||||
if (mode == null)
|
||||
{
|
||||
Debug.LogWarning("[InputHandler] PopInputMode called with null mode.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_inputModeStack.Count == 0)
|
||||
{
|
||||
Debug.LogWarning($"[InputHandler] PopInputMode '{mode.ModeName}' but stack is empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_inputModeStack.Peek() != mode)
|
||||
{
|
||||
Debug.LogWarning($"[InputHandler] PopInputMode '{mode.ModeName}' but top is '{_inputModeStack.Peek().ModeName}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
_inputModeStack.Pop();
|
||||
mode.Deactivate();
|
||||
SyncCoreMovementSuspension();
|
||||
|
||||
if (_inputModeStack.Count == 0)
|
||||
ResumeExtensions();
|
||||
}
|
||||
|
||||
private void SyncCoreMovementSuspension()
|
||||
{
|
||||
if (_movementActionMap == null)
|
||||
return;
|
||||
|
||||
bool shouldSuspend = false;
|
||||
foreach (InputMode mode in _inputModeStack)
|
||||
{
|
||||
if (mode.SuspendsCoreMovement)
|
||||
{
|
||||
shouldSuspend = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldSuspend && _movementActionMap.enabled)
|
||||
{
|
||||
_movementActionMap.Disable();
|
||||
ResetMovementState();
|
||||
}
|
||||
else if (!shouldSuspend && !_movementActionMap.enabled)
|
||||
_movementActionMap.Enable();
|
||||
}
|
||||
|
||||
private void RegisterActionCallbacks()
|
||||
{
|
||||
BindAll(moveActionName, context =>
|
||||
{
|
||||
MoveDirection = context.ReadValue<Vector2>();
|
||||
IsMoving = MoveDirection.sqrMagnitude > 0.0001f;
|
||||
});
|
||||
|
||||
BindAll(jumpActionName, context =>
|
||||
{
|
||||
if (context.started)
|
||||
IsJumpHeld = true;
|
||||
else if (context.canceled)
|
||||
IsJumpHeld = false;
|
||||
|
||||
if (context.performed)
|
||||
JumpEvent?.Invoke();
|
||||
});
|
||||
|
||||
BindAll(crouchActionName, context =>
|
||||
{
|
||||
if (context.started)
|
||||
{
|
||||
IsCrouching = true;
|
||||
CrouchEvent?.Invoke();
|
||||
}
|
||||
else if (context.canceled)
|
||||
{
|
||||
IsCrouching = false;
|
||||
}
|
||||
});
|
||||
|
||||
BindAll(proneActionName, context =>
|
||||
{
|
||||
if (!context.performed)
|
||||
return;
|
||||
|
||||
IsProne = !IsProne;
|
||||
ProneEvent?.Invoke();
|
||||
});
|
||||
|
||||
BindAll(dashActionName, context =>
|
||||
{
|
||||
if (context.performed)
|
||||
DashEvent?.Invoke();
|
||||
});
|
||||
|
||||
BindAll(walkActionName, context =>
|
||||
{
|
||||
if (context.started)
|
||||
IsWalking = true;
|
||||
else if (context.canceled)
|
||||
IsWalking = false;
|
||||
});
|
||||
|
||||
BindAll(sprintActionName, context =>
|
||||
{
|
||||
if (context.started)
|
||||
IsSprinting = true;
|
||||
else if (context.canceled)
|
||||
IsSprinting = false;
|
||||
});
|
||||
}
|
||||
|
||||
private void SuspendExtensions()
|
||||
{
|
||||
if (_extensionModules == null)
|
||||
return;
|
||||
|
||||
foreach (InputExtensionModule module in _extensionModules)
|
||||
module.Suspend();
|
||||
}
|
||||
|
||||
private void ResumeExtensions()
|
||||
{
|
||||
if (_extensionModules == null)
|
||||
return;
|
||||
|
||||
foreach (InputExtensionModule module in _extensionModules)
|
||||
module.Resume();
|
||||
}
|
||||
|
||||
private void BindAll(string actionName, Action<InputAction.CallbackContext> callback)
|
||||
{
|
||||
// An empty name means the project deliberately does not use that action.
|
||||
if (string.IsNullOrWhiteSpace(actionName))
|
||||
return;
|
||||
|
||||
InputAction action = _movementActionMap.FindAction(actionName, throwIfNotFound: false);
|
||||
if (action == null)
|
||||
{
|
||||
if (warnOnMissingActions)
|
||||
{
|
||||
Debug.LogWarning(
|
||||
$"[InputHandler] Action '{actionName}' was not found in map "
|
||||
+ $"'{movementActionMapName}'. That input will do nothing. Rename it under "
|
||||
+ "Action Names, clear the field to disable it, or turn off "
|
||||
+ "Warn On Missing Actions.",
|
||||
this);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
action.started += callback;
|
||||
action.performed += callback;
|
||||
action.canceled += callback;
|
||||
|
||||
if (!_callbackRegistry.TryGetValue(action, out List<Action<InputAction.CallbackContext>> callbacks))
|
||||
{
|
||||
callbacks = new List<Action<InputAction.CallbackContext>>();
|
||||
_callbackRegistry[action] = callbacks;
|
||||
}
|
||||
|
||||
callbacks.Add(callback);
|
||||
}
|
||||
|
||||
private void ResetMovementState()
|
||||
{
|
||||
MoveDirection = Vector2.zero;
|
||||
IsMoving = false;
|
||||
IsJumpHeld = false;
|
||||
IsCrouching = false;
|
||||
IsSprinting = false;
|
||||
IsWalking = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c28644d793744314bf329a2c98da20fc
|
||||
timeCreated: 1701815180
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Input/InputHandler.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,44 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
namespace CharacterMovement
|
||||
{
|
||||
public abstract class InputMode
|
||||
{
|
||||
public abstract string ModeName { get; }
|
||||
|
||||
public virtual bool SuspendsCoreMovement => false;
|
||||
|
||||
protected InputActionAsset[] InputAssets { get; private set; }
|
||||
|
||||
internal void Activate(InputActionAsset[] assets)
|
||||
{
|
||||
InputAssets = assets;
|
||||
OnActivate();
|
||||
}
|
||||
|
||||
internal void Deactivate()
|
||||
{
|
||||
OnDeactivate();
|
||||
}
|
||||
|
||||
protected virtual void OnActivate() { }
|
||||
protected virtual void OnDeactivate() { }
|
||||
|
||||
protected InputActionMap FindMap(string mapName)
|
||||
{
|
||||
if (InputAssets == null)
|
||||
return null;
|
||||
|
||||
foreach (InputActionAsset asset in InputAssets)
|
||||
{
|
||||
InputActionMap map = asset?.FindActionMap(mapName, throwIfNotFound: false);
|
||||
if (map != null)
|
||||
return map;
|
||||
}
|
||||
|
||||
Debug.LogWarning($"[{GetType().Name}] Action map '{mapName}' not found.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cd3e40818edc3af45840159f25008f47
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Input/InputMode.cs
|
||||
uploadId: 997018
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3f4aa7e8e1b435086a1e379ecefbe5b
|
||||
ScriptedImporter:
|
||||
internalIDToNameTable: []
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
script: {fileID: 11500000, guid: 8404be70184654265930450def6a9037, type: 3}
|
||||
generateWrapperCode: 0
|
||||
wrapperCodePath:
|
||||
wrapperClassName:
|
||||
wrapperCodeNamespace:
|
||||
AssetOrigin:
|
||||
serializedVersion: 1
|
||||
productId: 367142
|
||||
packageName: "MotionCore \u2013 Physics Character Controller"
|
||||
packageVersion: 1.2
|
||||
assetPath: Assets/Character Controller/Core/Scripts/Input/InputSystem_Actions.inputactions
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace CharacterMovement
|
||||
{
|
||||
/// <summary>
|
||||
/// How the sprint input is interpreted.
|
||||
/// </summary>
|
||||
public enum SprintActivationMode
|
||||
{
|
||||
/// <summary>Sprint only while the input is held. The common default for action games.</summary>
|
||||
Hold = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A press switches sprinting on and off. Releasing the movement input also ends it, so the
|
||||
/// character does not silently sprint again the next time the player moves.
|
||||
/// </summary>
|
||||
Toggle = 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cf9219a641ec43319c0d263da75dec2f
|
||||
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/Input/SprintActivationMode.cs
|
||||
uploadId: 997018
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 060b78eaf20846f891059663010eb354
|
||||
timeCreated: 1701807615
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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:
|
||||
+91
@@ -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() => controller.AddMovementModifier(this);
|
||||
/// private void OnDisable() => controller.RemoveMovementModifier(this);
|
||||
///
|
||||
/// public void ApplyMovementModifiers(ref CharacterMovementModifiers modifiers)
|
||||
/// {
|
||||
/// if (stamina.Current <= 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);
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
+57
@@ -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
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
+47
@@ -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
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
+53
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
+154
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
+545
@@ -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];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
}
|
||||
}
|
||||
+18
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
+225
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
Loaded 100 of 875 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user