Fix player jitter on moving platforms
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
[DefaultExecutionOrder(1001)]
|
||||
public class CameraThirdPerson : MonoBehaviour
|
||||
{
|
||||
[System.Serializable]
|
||||
@@ -39,6 +40,7 @@ public class CameraThirdPerson : MonoBehaviour
|
||||
public class References
|
||||
{
|
||||
public InputActionAsset InputActions;
|
||||
public Transform Target;
|
||||
}
|
||||
|
||||
[SerializeField]
|
||||
@@ -96,7 +98,7 @@ public class CameraThirdPerson : MonoBehaviour
|
||||
|
||||
private void SetCursor()
|
||||
{
|
||||
bool lockCursor = Player.Owner && !Player.Owner.State.IsPaused;
|
||||
bool lockCursor = Player.Instance && !Player.Instance.State.IsPaused;
|
||||
|
||||
Cursor.lockState = lockCursor ? CursorLockMode.Locked : CursorLockMode.None;
|
||||
Cursor.visible = !lockCursor;
|
||||
@@ -104,7 +106,7 @@ public class CameraThirdPerson : MonoBehaviour
|
||||
|
||||
private void SetYawAndPitch(float deltaTime)
|
||||
{
|
||||
if (!Player.Owner || Player.Owner.State.IsPaused)
|
||||
if ((!Player.Instance || Player.Instance.State.IsPaused) && !_references.Target)
|
||||
return;
|
||||
|
||||
Vector2 lookInput = _lookAction?.ReadValue<Vector2>() ?? Vector2.zero;
|
||||
@@ -132,9 +134,11 @@ public class CameraThirdPerson : MonoBehaviour
|
||||
{
|
||||
Vector3 offset = Vector3.up * _settings.VerticalOffset;
|
||||
|
||||
if (!Player.Owner)
|
||||
return Vector3.zero + offset;
|
||||
if (_references.Target)
|
||||
return _references.Target.position + offset;
|
||||
else if(Player.Instance)
|
||||
return Player.Instance.transform.position + offset;
|
||||
|
||||
return Player.Owner.transform.position + offset;
|
||||
return Vector3.zero + offset;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ public class FallingPlatform : MonoBehaviour
|
||||
|
||||
void OnTriggerEnter(Collider col)
|
||||
{
|
||||
if (Player.Owner && Player.Owner.gameObject == col.gameObject)
|
||||
if (Player.Instance && Player.Instance.gameObject == col.gameObject)
|
||||
{
|
||||
Fall();
|
||||
}
|
||||
|
||||
129
Assets/Content/Scripts/JetPack.cs
Normal file
129
Assets/Content/Scripts/JetPack.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
using Unity.VisualScripting;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
public class JetPack : MonoBehaviour
|
||||
{
|
||||
[System.Serializable]
|
||||
public class Settings
|
||||
{
|
||||
public float Force = 5;
|
||||
public float Duration = 10;
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public class References
|
||||
{
|
||||
public BoxCollider Collider;
|
||||
public SphereCollider Trigger;
|
||||
public Rigidbody Rigidbody;
|
||||
public ParticleSystem Particles;
|
||||
public InputActionAsset InputActions;
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public class StateContainer
|
||||
{
|
||||
public bool Equiped;
|
||||
}
|
||||
|
||||
[SerializeField]
|
||||
public Settings _settings;
|
||||
|
||||
[SerializeField]
|
||||
public References _references;
|
||||
|
||||
[SerializeField]
|
||||
public StateContainer _state;
|
||||
|
||||
private bool _wasPressed;
|
||||
private float _duration = 0;
|
||||
private float _smooth = 0;
|
||||
|
||||
private InputAction _jumpAction;
|
||||
|
||||
void OnTriggerEnter(Collider col)
|
||||
{
|
||||
if (Player.Instance && Player.Instance.gameObject == col.gameObject)
|
||||
{
|
||||
Equip();
|
||||
}
|
||||
}
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_duration = _settings.Duration;
|
||||
_jumpAction = _references.InputActions.FindActionMap("Player").FindAction("Jump");
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (_state.Equiped && Player.Instance)
|
||||
{
|
||||
if (_duration > 0)
|
||||
{
|
||||
if (_jumpAction.IsPressed())
|
||||
{
|
||||
_wasPressed = true;
|
||||
_duration -= Time.deltaTime;
|
||||
_smooth = Mathf.Clamp01(_smooth + Time.deltaTime);
|
||||
//Player.Instance.SetExtraForce(Vector3.up * _settings.Force * _smooth, true);
|
||||
}
|
||||
else if (_wasPressed)
|
||||
{
|
||||
_smooth = 0;
|
||||
_wasPressed = false;
|
||||
ResetExtraForce();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Unequip();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Equip()
|
||||
{
|
||||
if (_state.Equiped || _duration <= 0 ||!Player.Instance)
|
||||
return;
|
||||
|
||||
_wasPressed = false;
|
||||
_state.Equiped = true;
|
||||
_duration = _settings.Duration;
|
||||
|
||||
_references.Collider.enabled = false;
|
||||
_references.Trigger.enabled = false;
|
||||
_references.Rigidbody.isKinematic = true;
|
||||
|
||||
transform.parent = Player.Instance.transform.GetChild(0).GetChild(1).GetChild(0);
|
||||
transform.localPosition = new Vector3(0, .3f, -.4f);
|
||||
transform.localEulerAngles = Vector3.zero;
|
||||
}
|
||||
|
||||
private void Unequip()
|
||||
{
|
||||
if (!_state.Equiped)
|
||||
return;
|
||||
|
||||
ResetExtraForce();
|
||||
|
||||
_state.Equiped = false;
|
||||
_duration = _settings.Duration;
|
||||
|
||||
transform.parent = null;
|
||||
|
||||
Vector3 random = new Vector3(UnityEngine.Random.Range(-1, 1), UnityEngine.Random.Range(-1, 1), UnityEngine.Random.Range(-1, 1)).normalized;
|
||||
|
||||
_references.Collider.enabled = true;
|
||||
_references.Trigger.enabled = false;
|
||||
_references.Rigidbody.isKinematic = false;
|
||||
_references.Rigidbody.AddRelativeTorque(random, ForceMode.Impulse);
|
||||
}
|
||||
|
||||
|
||||
private void ResetExtraForce()
|
||||
{
|
||||
//Player.Instance.SetExtraForce(Vector3.zero, false);
|
||||
}
|
||||
}
|
||||
2
Assets/Content/Scripts/JetPack.cs.meta
Normal file
2
Assets/Content/Scripts/JetPack.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e22ce2b6f35d2f441b3b72c98bfd81a4
|
||||
22
Assets/Content/Scripts/ParentSimuator.cs
Normal file
22
Assets/Content/Scripts/ParentSimuator.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using UnityEngine;
|
||||
|
||||
[DefaultExecutionOrder(1)]
|
||||
public class ParentSimuator : MonoBehaviour
|
||||
{
|
||||
[SerializeField] Transform _target;
|
||||
[SerializeField] Vector3 _targetPosition;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
_targetPosition = _target.InverseTransformPoint(transform.position);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
Vector3 targetPosition = _target.TransformPoint(_targetPosition);
|
||||
|
||||
transform.position = targetPosition;
|
||||
|
||||
_targetPosition = _target.InverseTransformPoint(transform.position);
|
||||
}
|
||||
}
|
||||
2
Assets/Content/Scripts/ParentSimuator.cs.meta
Normal file
2
Assets/Content/Scripts/ParentSimuator.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 98c2f408a2e65a54da421fc54a4f07f3
|
||||
@@ -1,22 +1,15 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
//using Unity.Netcode;
|
||||
//using Unity.Netcode.Components;
|
||||
using System;
|
||||
|
||||
/// <summary>
|
||||
/// Player controller.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(CharacterController))]
|
||||
public class Player : MonoBehaviour //NetworkBehaviour
|
||||
[DefaultExecutionOrder(1000)]
|
||||
public class Player : MonoBehaviour
|
||||
{
|
||||
public static Player Owner { get; private set; }
|
||||
|
||||
public enum PlayerType
|
||||
{
|
||||
Local,
|
||||
//Network
|
||||
}
|
||||
public static Player Instance { get; private set; }
|
||||
|
||||
public enum PlayerState
|
||||
{
|
||||
@@ -33,8 +26,6 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
[System.Serializable]
|
||||
public class Settings
|
||||
{
|
||||
public PlayerType Type;
|
||||
|
||||
[Header("Movements")]
|
||||
|
||||
[Tooltip("Movement speed in km/h")]
|
||||
@@ -51,7 +42,7 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
|
||||
[Tooltip("Layers considered as ground")]
|
||||
public LayerMask GroundLayer = 1;
|
||||
|
||||
|
||||
[Header("Debug")]
|
||||
|
||||
[Tooltip("GUI logs of current state")]
|
||||
@@ -63,7 +54,6 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
{
|
||||
public CharacterController Controller;
|
||||
public InputActionAsset InputActions;
|
||||
//public NetworkTransform NetworkTransform;
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
@@ -78,23 +68,14 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
[Tooltip("Is player grounded?")]
|
||||
public bool IsGrounded;
|
||||
|
||||
[Tooltip("Is gravity suspended?")]
|
||||
public bool IsGravitySuspended;
|
||||
|
||||
[Tooltip("Vertical velocity in m/s")]
|
||||
public float VerticalVelocity;
|
||||
|
||||
[Tooltip("Horizontal velocity in m/s")]
|
||||
public Vector2 HorizontalVelocity;
|
||||
|
||||
[Tooltip("Additionnal velocity in m/s")]
|
||||
public Vector3 ExtraVelocity;
|
||||
|
||||
[Tooltip("Ground velocity in m/s to avoid parenting")]
|
||||
public Vector3 GroundVelocity;
|
||||
[Tooltip("Current velocity in m/s")]
|
||||
public Vector3 Velocity;
|
||||
|
||||
[Tooltip("Ground transform evaluated as parent")]
|
||||
public Transform GroundTransform;
|
||||
public Transform Ground;
|
||||
|
||||
public float VerticalVelocity => Velocity.y;
|
||||
public Vector3 HorizontalVelocity => new Vector3(Velocity.x, 0, Velocity.z);
|
||||
}
|
||||
|
||||
[SerializeField] private Settings _settings;
|
||||
@@ -104,84 +85,32 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
public StateContainer State => _state;
|
||||
|
||||
#region Private Fields
|
||||
private bool _jumpInput;
|
||||
private Vector2 _moveInput;
|
||||
|
||||
private InputAction _moveAction;
|
||||
private InputAction _jumpAction;
|
||||
|
||||
private Camera _camera;
|
||||
|
||||
// Ground check geometry
|
||||
private Vector3 _groundCheckRayOffset;
|
||||
private Vector3 _groundCheckSphereOffset;
|
||||
private float _groundCheckRadius;
|
||||
private Vector3 _groundCheckOffset;
|
||||
private Vector3 _groundContactPosition;
|
||||
private Quaternion _groundContactRotation;
|
||||
private Collider[] _groundCheckResults = new Collider[1];
|
||||
|
||||
IEnumerator _addExtraForceCoroutine;
|
||||
|
||||
// OverlapSphere results buffer (non-alloc)
|
||||
private Collider[] _overlapResults = new Collider[1];
|
||||
|
||||
// Platform tracking
|
||||
private Vector3 _lastPlatformPosition;
|
||||
private Quaternion _lastPlatformRotation;
|
||||
|
||||
// Events
|
||||
public event Action<PlayerState, PlayerState> OnStateChanged;
|
||||
#endregion
|
||||
|
||||
#region Constants
|
||||
private const float GRAVITY = -20;
|
||||
private const float KMH_TO_MS = 1 / 3.6f;
|
||||
private const float GROUND_STICK_FORCE = -2;
|
||||
#endregion
|
||||
|
||||
#region Network
|
||||
const bool IsOwner = true; // Remove when enable Network
|
||||
/*
|
||||
// Network variables to synchronize state
|
||||
private NetworkVariable<PlayerState> _networkCurrentState = new NetworkVariable<PlayerState>(
|
||||
PlayerState.Idle,
|
||||
NetworkVariableReadPermission.Everyone,
|
||||
NetworkVariableWritePermission.Owner
|
||||
);
|
||||
|
||||
private NetworkVariable<Vector2> _networkHorizontalVelocity = new NetworkVariable<Vector2>(
|
||||
Vector2.zero,
|
||||
NetworkVariableReadPermission.Everyone,
|
||||
NetworkVariableWritePermission.Owner
|
||||
);
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
base.OnNetworkSpawn();
|
||||
|
||||
_references.NetworkTransform.Interpolate = !IsOwner;
|
||||
|
||||
if (IsOwner)
|
||||
{
|
||||
Init();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Subscribe to NetworkVariable changes for non-owners
|
||||
_networkCurrentState.OnValueChanged += OnNetworkStateChanged;
|
||||
_networkHorizontalVelocity.OnValueChanged += OnNetworkHorizontalVelocityChanged;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
base.OnNetworkDespawn();
|
||||
|
||||
// Unsubscribe from NetworkVariable changes
|
||||
if (!IsOwner)
|
||||
{
|
||||
_networkCurrentState.OnValueChanged -= OnNetworkStateChanged;
|
||||
_networkHorizontalVelocity.OnValueChanged -= OnNetworkHorizontalVelocityChanged;
|
||||
}
|
||||
}
|
||||
|
||||
// Callback when player state changes (for non-owners)
|
||||
private void OnNetworkStateChanged(PlayerState previousState, PlayerState newState)
|
||||
{
|
||||
_state.CurrentState = newState;
|
||||
}
|
||||
|
||||
// Callback when horizontal velocity changes (for non-owners)
|
||||
private void OnNetworkHorizontalVelocityChanged(Vector2 previousVelocity, Vector2 newVelocity)
|
||||
{
|
||||
_state.HorizontalVelocity = newVelocity;
|
||||
}*/
|
||||
private const float STICK_FORCE = -5f;
|
||||
private const float GRAVITY = -20f;
|
||||
private const float MAX_GRAVITY = -50f;
|
||||
#endregion
|
||||
|
||||
#region Unity Debug
|
||||
@@ -194,36 +123,57 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
style.normal.textColor = Color.white;
|
||||
style.alignment = TextAnchor.UpperLeft;
|
||||
|
||||
string debug = $"Horizontal Velocity: {_state.HorizontalVelocity.magnitude / KMH_TO_MS:F2} km/h\n";
|
||||
debug += $"X: {_state.HorizontalVelocity.x:F2} Z: {_state.HorizontalVelocity.y:F2}\n";
|
||||
debug += $"Vertical Velocity: {_state.VerticalVelocity / KMH_TO_MS:F2} km/h\n";
|
||||
debug += $"Grounded: {_state.IsGrounded}\n";
|
||||
debug += $"State: {_state.CurrentState}\n";
|
||||
//debug += $"IsOwner: {IsOwner}\n";
|
||||
//debug += $"IsServer: {IsServer}\n";
|
||||
//debug += $"IsClient: {IsClient}";
|
||||
|
||||
GUI.Label(new Rect(10, 10, 400, 200), debug, style);
|
||||
GUILayout.BeginArea(new Rect(10, 10, 400, 200));
|
||||
GUILayout.Label($"State: {_state.CurrentState}", style);
|
||||
GUILayout.Label($"Grounded: {_state.IsGrounded}", style);
|
||||
GUILayout.Label($"Velocity: {_state.Velocity.magnitude:F2} m/s", style);
|
||||
GUILayout.EndArea();
|
||||
}
|
||||
}
|
||||
|
||||
void OnDrawGizmos()
|
||||
{
|
||||
if (_settings.Type == PlayerType.Local || IsOwner)
|
||||
{
|
||||
// Draw ground check sphere
|
||||
Gizmos.matrix = transform.localToWorldMatrix;
|
||||
Gizmos.color = _state.IsGrounded ? Color.green : new Color(1, .5f, 0);
|
||||
Gizmos.DrawWireSphere(_groundCheckOffset, _groundCheckRadius);
|
||||
}
|
||||
Color c = _state.IsGrounded ? Color.green : new Color(1, .5f, 0);
|
||||
|
||||
Gizmos.color = c;
|
||||
Gizmos.DrawRay(transform.position + _groundCheckRayOffset, Vector3.down * (_settings.GroundTolerance * 2f));
|
||||
Gizmos.DrawWireSphere(transform.position + _groundCheckSphereOffset, _groundCheckRadius);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Unity Lifecycle
|
||||
void Awake()
|
||||
{
|
||||
if (Instance != null && Instance != this)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
Instance = this;
|
||||
|
||||
if (_references.Controller == null)
|
||||
_references.Controller = GetComponent<CharacterController>();
|
||||
|
||||
_camera = Camera.main;
|
||||
|
||||
_moveAction = _references.InputActions.FindActionMap("Player").FindAction("Move");
|
||||
_jumpAction = _references.InputActions.FindActionMap("Player").FindAction("Jump");
|
||||
|
||||
_references.Controller.skinWidth = 0.08f;
|
||||
_references.Controller.minMoveDistance = 0f;
|
||||
_references.Controller.stepOffset = 0.4f;
|
||||
|
||||
CharacterController cc = _references.Controller;
|
||||
|
||||
_groundCheckRayOffset = cc.center + Vector3.up * (-cc.height * .5f - cc.skinWidth + _settings.GroundTolerance);
|
||||
_groundCheckSphereOffset = cc.center + Vector3.up * (-cc.height * .5f + cc.radius - cc.skinWidth - _settings.GroundTolerance);
|
||||
_groundCheckRadius = cc.radius;
|
||||
}
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
if (_settings.Type == PlayerType.Local)
|
||||
Init();
|
||||
_moveAction?.Enable();
|
||||
_jumpAction?.Enable();
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
@@ -234,80 +184,26 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (_settings.Type == PlayerType.Local || IsOwner)
|
||||
{
|
||||
float deltaTime = Time.deltaTime;
|
||||
if (_state.IsPaused) return;
|
||||
|
||||
GetInputs();
|
||||
CheckGround(deltaTime);
|
||||
SetVelocity(deltaTime);
|
||||
SetMovement(deltaTime);
|
||||
UpdateState();
|
||||
}
|
||||
}
|
||||
float deltaTime = Time.deltaTime;
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
// Owner sends state to network
|
||||
if (IsOwner)
|
||||
{
|
||||
//_networkCurrentState.Value = _state.CurrentState;
|
||||
//_networkHorizontalVelocity.Value = _state.HorizontalVelocity;
|
||||
}
|
||||
SetPlatformOffset();
|
||||
SetGravity(deltaTime);
|
||||
SetVelocity(deltaTime);
|
||||
SetJump();
|
||||
SetMovement(deltaTime);
|
||||
SetState();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Physics
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
/// <summary>
|
||||
/// Add an additionnal force to the player.
|
||||
/// </summary>
|
||||
/// <param name="force">Force direction in m/s</param>
|
||||
/// <param name="suspendGravity">Suspend gravity for the duration of the force</param>
|
||||
/// <param name="duration">Duration while fore is applied (if 0: infinite duration)</param>
|
||||
/// <param name="curve">A remplir par claude</param>
|
||||
public void AddExtraForce(Vector3 force, bool suspendGravity, float duration = -1, AnimationCurve curve = null)
|
||||
{
|
||||
if (_state.CurrentState == PlayerState.Eliminated)
|
||||
return;
|
||||
|
||||
if (_addExtraForceCoroutine != null)
|
||||
return;
|
||||
|
||||
if (duration <= 0)
|
||||
_state.ExtraVelocity = force;
|
||||
else
|
||||
StartCoroutine(_addExtraForceCoroutine = AddExtraForceCoroutine(force, suspendGravity, duration, curve));
|
||||
}
|
||||
|
||||
private IEnumerator AddExtraForceCoroutine(Vector3 force, bool suspendGravity, float duration, AnimationCurve curve)
|
||||
{
|
||||
if (suspendGravity)
|
||||
_state.IsGravitySuspended = true;
|
||||
|
||||
for (float t = 0f; t < duration; t += Time.deltaTime)
|
||||
{
|
||||
float normaliwedTime = t / duration;
|
||||
float easeTime = curve != null ? curve.Evaluate(normaliwedTime) : normaliwedTime;
|
||||
|
||||
_state.ExtraVelocity = force * easeTime;
|
||||
|
||||
yield return new WaitForEndOfFrame();
|
||||
}
|
||||
|
||||
if (suspendGravity)
|
||||
_state.IsGravitySuspended = false;
|
||||
|
||||
_state.ExtraVelocity = Vector3.zero;
|
||||
_addExtraForceCoroutine = null;
|
||||
}
|
||||
|
||||
public void ResetExtraForce()
|
||||
{
|
||||
_state.ExtraVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stuns the player for a specified duration (0 = infinite).
|
||||
/// Stuns for a specified duration (0 = infinite).
|
||||
/// </summary>
|
||||
public void Stun(float duration = 0)
|
||||
{
|
||||
@@ -315,15 +211,14 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
return;
|
||||
|
||||
_state.CurrentState = PlayerState.Stunned;
|
||||
_state.HorizontalVelocity = Vector2.zero;
|
||||
_state.VerticalVelocity = 0f;
|
||||
_state.Velocity = Vector3.zero;
|
||||
|
||||
if (duration > 0)
|
||||
Invoke(nameof(RecoverFromStun), duration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recover the player from stun.
|
||||
/// Recover from stun.
|
||||
/// </summary>
|
||||
public void RecoverFromStun()
|
||||
{
|
||||
@@ -337,8 +232,7 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
public void Eliminate()
|
||||
{
|
||||
_state.CurrentState = PlayerState.Eliminated;
|
||||
_state.HorizontalVelocity = Vector2.zero;
|
||||
_state.VerticalVelocity = 0f;
|
||||
_state.Velocity = Vector3.zero;
|
||||
_references.Controller.enabled = false;
|
||||
}
|
||||
|
||||
@@ -352,228 +246,116 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
#endregion
|
||||
|
||||
#region Player Logic
|
||||
private void Init()
|
||||
private void SetPlatformOffset()
|
||||
{
|
||||
if (_settings.Type == PlayerType.Local || IsOwner)
|
||||
{
|
||||
if (Owner == null)
|
||||
{
|
||||
Owner = this;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning($"Multiple Player instances detected. Destroy: {gameObject.name}");
|
||||
Destroy(gameObject);
|
||||
}
|
||||
// Raycast for center contact
|
||||
Vector3 rayOrigin = transform.position + _groundCheckRayOffset;
|
||||
bool rayHit = Physics.Raycast(rayOrigin, Vector3.down, out RaycastHit rayInfo, _settings.GroundTolerance * 2f, _settings.GroundLayer);
|
||||
|
||||
_moveAction = _references.InputActions.FindActionMap("Player").FindAction("Move");
|
||||
_jumpAction = _references.InputActions.FindActionMap("Player").FindAction("Jump");
|
||||
// OverlapSphere for edge contact
|
||||
Vector3 sphereOrigin = transform.position + _groundCheckSphereOffset;
|
||||
int overlapCount = Physics.OverlapSphereNonAlloc(sphereOrigin, _groundCheckRadius, _overlapResults, _settings.GroundLayer);
|
||||
bool sphereHit = overlapCount > 0;
|
||||
|
||||
_moveAction?.Enable();
|
||||
_jumpAction?.Enable();
|
||||
}
|
||||
|
||||
_groundCheckOffset = _references.Controller.center + Vector3.up * (_references.Controller.height * -.5f + _references.Controller.radius - _references.Controller.skinWidth - _settings.GroundTolerance);
|
||||
_groundCheckRadius = _references.Controller.radius;
|
||||
}
|
||||
|
||||
private void GetInputs()
|
||||
{
|
||||
if (Keyboard.current?.escapeKey.wasPressedThisFrame ?? false)
|
||||
Pause(!_state.IsPaused);
|
||||
|
||||
_moveInput = _moveAction != null ? _moveAction.ReadValue<Vector2>() : Vector2.zero;
|
||||
|
||||
bool jumpInput = _jumpAction != null && _jumpAction.WasPressedThisFrame();
|
||||
if (jumpInput)
|
||||
{
|
||||
bool canJump = _state.IsGrounded &&
|
||||
_state.CurrentState != PlayerState.Stunned &&
|
||||
_state.CurrentState != PlayerState.Eliminated &&
|
||||
_state.CurrentState != PlayerState.Jumping &&
|
||||
_state.CurrentState != PlayerState.Falling;
|
||||
|
||||
_jumpInput = canJump;
|
||||
}
|
||||
else
|
||||
{
|
||||
_jumpInput = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckGround(float deltaTime)
|
||||
{
|
||||
int hitCount = Physics.OverlapSphereNonAlloc(
|
||||
transform.position + transform.rotation * _groundCheckOffset,
|
||||
_groundCheckRadius,
|
||||
_groundCheckResults,
|
||||
_settings.GroundLayer
|
||||
);
|
||||
|
||||
bool wasGrounded = _state.IsGrounded;
|
||||
_state.IsGrounded = hitCount > 0;
|
||||
_state.IsGrounded = rayHit || sphereHit;
|
||||
|
||||
if (_state.IsGrounded)
|
||||
{
|
||||
Transform newPlatform = _groundCheckResults[0].transform;
|
||||
Transform currentGround = rayHit ? rayInfo.collider.transform : _overlapResults[0].transform;
|
||||
|
||||
// If platform changed, initialize last frame values
|
||||
if (newPlatform != _state.GroundTransform)
|
||||
// Initialize references when landing on a new surface to prevent teleporting
|
||||
if (currentGround != _state.Ground)
|
||||
{
|
||||
_state.GroundTransform = newPlatform;
|
||||
_state.GroundVelocity = Vector3.zero;
|
||||
_groundContactPosition = _state.GroundTransform.position;
|
||||
_groundContactRotation = _state.GroundTransform.rotation;
|
||||
_state.Ground = currentGround;
|
||||
_lastPlatformPosition = _state.Ground.position;
|
||||
_lastPlatformRotation = _state.Ground.rotation;
|
||||
return;
|
||||
}
|
||||
|
||||
// Yaw delta: rotate player around platform pivot
|
||||
Quaternion rotationDelta = _state.Ground.rotation * Quaternion.Inverse(_lastPlatformRotation);
|
||||
float platformYaw = rotationDelta.eulerAngles.y;
|
||||
|
||||
if (Mathf.Abs(platformYaw) > .001f)
|
||||
{
|
||||
Vector3 dir = transform.position - _state.Ground.position;
|
||||
dir = Quaternion.Euler(0, platformYaw, 0) * dir;
|
||||
transform.position = _state.Ground.position + dir;
|
||||
transform.Rotate(0, platformYaw, 0);
|
||||
}
|
||||
|
||||
// Translation delta
|
||||
transform.position += _state.Ground.position - _lastPlatformPosition;
|
||||
|
||||
// Store current state for next frame
|
||||
_lastPlatformPosition = _state.Ground.position;
|
||||
_lastPlatformRotation = _state.Ground.rotation;
|
||||
|
||||
// Sync physics broadphase to the new transform, the CharacterController
|
||||
// doesn't see a stale overlap and generate a corrective push
|
||||
Physics.SyncTransforms();
|
||||
}
|
||||
else
|
||||
{
|
||||
// If player just left the platform
|
||||
if (wasGrounded && _state.GroundTransform != null)
|
||||
{
|
||||
Vector3 platformVelocity = (_state.GroundTransform.position - _groundContactPosition) / deltaTime;
|
||||
|
||||
// Add platform velovity to player ground velocity
|
||||
_state.GroundVelocity = platformVelocity;
|
||||
}
|
||||
|
||||
_state.GroundTransform = null;
|
||||
_state.Ground = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetGravity(float deltaTime)
|
||||
{
|
||||
if (_state.IsGrounded && _state.Velocity.y < 0)
|
||||
_state.Velocity.y = STICK_FORCE;
|
||||
else
|
||||
_state.Velocity.y = Mathf.Max(_state.Velocity.y + GRAVITY * deltaTime, MAX_GRAVITY);
|
||||
}
|
||||
|
||||
private void SetVelocity(float deltaTime)
|
||||
{
|
||||
// Determine movement attenuation based on current state
|
||||
Vector2 input = _moveAction.ReadValue<Vector2>();
|
||||
Vector3 forward = Vector3.ProjectOnPlane(_camera.transform.forward, Vector3.up).normalized;
|
||||
Vector3 right = Vector3.ProjectOnPlane(_camera.transform.right, Vector3.up).normalized;
|
||||
|
||||
float moveAtten;
|
||||
switch (_state.CurrentState)
|
||||
float speed = _settings.Speed * KMH_TO_MS;
|
||||
Vector3 moveInput = (forward * input.y + right * input.x) * speed;
|
||||
|
||||
_state.Velocity.x = moveInput.x;
|
||||
_state.Velocity.z = moveInput.z;
|
||||
|
||||
if (moveInput.sqrMagnitude > 0.001f)
|
||||
{
|
||||
case PlayerState.Idle:
|
||||
case PlayerState.Moving:
|
||||
moveAtten = 1;
|
||||
break;
|
||||
case PlayerState.Jumping:
|
||||
moveAtten = .8f;
|
||||
break;
|
||||
case PlayerState.Falling:
|
||||
moveAtten = .6f;
|
||||
break;
|
||||
default:
|
||||
moveAtten = 0;
|
||||
break;
|
||||
Quaternion targetRot = Quaternion.LookRotation(moveInput);
|
||||
float step = _settings.RotationSpeed * deltaTime;
|
||||
Vector3 euler = Quaternion.Slerp(transform.rotation, targetRot, step).eulerAngles;
|
||||
transform.rotation = Quaternion.Euler(0, euler.y, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Update horizontal velocity
|
||||
|
||||
Vector2 horizontalVelocity = _state.HorizontalVelocity;
|
||||
|
||||
if (moveAtten > 0 && Camera.main)
|
||||
private void SetJump()
|
||||
{
|
||||
if (_jumpAction.triggered && _state.IsGrounded)
|
||||
{
|
||||
Vector2 move = Vector2.zero;
|
||||
|
||||
// Don't apply move to velocity if paused
|
||||
if (!_state.IsPaused)
|
||||
{
|
||||
Vector3 forward = Camera.main.transform.forward;
|
||||
Vector3 right = Camera.main.transform.right;
|
||||
|
||||
forward.y = right.y = 0;
|
||||
forward.Normalize();
|
||||
right.Normalize();
|
||||
|
||||
Vector3 direction3D = (forward * _moveInput.y + right * _moveInput.x);
|
||||
move = new Vector2(direction3D.x, direction3D.z).normalized;
|
||||
move *= _settings.Speed * KMH_TO_MS;
|
||||
}
|
||||
|
||||
horizontalVelocity = Vector2.Lerp(horizontalVelocity, move, moveAtten * deltaTime * 5);
|
||||
_state.Velocity.y = _settings.JumpForce;
|
||||
_state.Ground = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
horizontalVelocity = Vector2.zero;
|
||||
}
|
||||
|
||||
_state.HorizontalVelocity = horizontalVelocity.magnitude > .01f ? horizontalVelocity : Vector2.zero;
|
||||
|
||||
// Update vertical velocity
|
||||
|
||||
float verticalVelocity = _state.VerticalVelocity;
|
||||
|
||||
if (_state.IsGrounded && _jumpInput && !_state.IsPaused)
|
||||
{
|
||||
_state.IsGrounded = _jumpInput = false;
|
||||
verticalVelocity = _settings.JumpForce;
|
||||
}
|
||||
else if (_state.IsGrounded && verticalVelocity <= 0)
|
||||
{
|
||||
verticalVelocity = _state.IsGravitySuspended ? 0 : GROUND_STICK_FORCE;
|
||||
}
|
||||
else if (!_state.IsGravitySuspended)
|
||||
{
|
||||
verticalVelocity = Mathf.Max(verticalVelocity + GRAVITY * deltaTime, GRAVITY);
|
||||
}
|
||||
|
||||
_state.VerticalVelocity = verticalVelocity;
|
||||
}
|
||||
|
||||
private void SetMovement(float deltaTime)
|
||||
{
|
||||
// Apply platform movement and rotation
|
||||
|
||||
if (_state.GroundTransform)
|
||||
{
|
||||
// Calculate platform delta position
|
||||
Vector3 platformPositionDelta = _state.GroundTransform.position - _groundContactPosition;
|
||||
|
||||
// Calculate platform delta rotation
|
||||
Quaternion platformRotationDelta = _state.GroundTransform.rotation * Quaternion.Inverse(_groundContactRotation);
|
||||
|
||||
// Apply rotation around platform center
|
||||
Vector3 localPosition = transform.position - _state.GroundTransform.position;
|
||||
Vector3 rotatedPosition = platformRotationDelta * localPosition;
|
||||
platformPositionDelta += rotatedPosition - localPosition;
|
||||
|
||||
// Move player with platform
|
||||
_references.Controller.Move(platformPositionDelta);
|
||||
|
||||
// Rotate player with platform
|
||||
transform.Rotate(Vector3.up, platformRotationDelta.eulerAngles.y, Space.World);
|
||||
|
||||
// Update last frame values
|
||||
_groundContactPosition = _state.GroundTransform.position;
|
||||
_groundContactRotation = _state.GroundTransform.rotation;
|
||||
}
|
||||
|
||||
// Apply player movement
|
||||
|
||||
Vector3 lookDir = new Vector3(_state.HorizontalVelocity.x, 0, _state.HorizontalVelocity.y);
|
||||
Vector3 velocity = lookDir;
|
||||
velocity.y = _state.VerticalVelocity;
|
||||
velocity += _state.GroundVelocity;
|
||||
velocity += _state.ExtraVelocity;
|
||||
velocity *= deltaTime;
|
||||
|
||||
_references.Controller.Move(velocity);
|
||||
|
||||
// Apply player rotation
|
||||
|
||||
if (lookDir.sqrMagnitude > .01f)
|
||||
{
|
||||
Quaternion targetRotation = Quaternion.LookRotation(lookDir, Vector3.up);
|
||||
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, _settings.RotationSpeed * deltaTime);
|
||||
}
|
||||
_references.Controller.Move(_state.Velocity * deltaTime);
|
||||
}
|
||||
|
||||
private void UpdateState()
|
||||
private void SetState()
|
||||
{
|
||||
PlayerState previousState = _state.CurrentState;
|
||||
|
||||
if (_state.CurrentState == PlayerState.Stunned ||
|
||||
_state.CurrentState == PlayerState.Eliminated)
|
||||
_state.CurrentState == PlayerState.Eliminated ||
|
||||
_state.CurrentState == PlayerState.Winner ||
|
||||
_state.CurrentState == PlayerState.Loser)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerState previousState = _state.CurrentState;
|
||||
|
||||
if (!_state.IsGrounded)
|
||||
{
|
||||
_state.CurrentState = _state.VerticalVelocity > 0
|
||||
@@ -582,14 +364,13 @@ public class Player : MonoBehaviour //NetworkBehaviour
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_state.VerticalVelocity <= 0)
|
||||
_state.CurrentState = _state.HorizontalVelocity.sqrMagnitude > 0.1f
|
||||
? PlayerState.Moving
|
||||
: PlayerState.Idle;
|
||||
_state.CurrentState = _state.HorizontalVelocity.sqrMagnitude > 0.1f
|
||||
? PlayerState.Moving
|
||||
: PlayerState.Idle;
|
||||
}
|
||||
|
||||
//if (_state.CurrentState != previousState)
|
||||
// Debug.Log($"{previousState} → {_state.CurrentState}");
|
||||
if (previousState != _state.CurrentState)
|
||||
OnStateChanged?.Invoke(previousState, _state.CurrentState);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
/// Procedural platform animation supporting translation, rotation, and scaling.
|
||||
/// Supports multiple animation types (Constant, PingPong, Loop, Single) with easing.
|
||||
/// </summary>
|
||||
[DefaultExecutionOrder(0)]
|
||||
public class ProceduralAnimator : MonoBehaviour
|
||||
{
|
||||
public enum AnimationSpace
|
||||
@@ -89,7 +90,7 @@ public class ProceduralAnimator : MonoBehaviour
|
||||
_state.IsFinished = false;
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
void Update()
|
||||
{
|
||||
if (_state.IsFinished)
|
||||
return;
|
||||
|
||||
@@ -10,10 +10,10 @@ public class Springboard : MonoBehaviour
|
||||
|
||||
void OnTriggerEnter(Collider col)
|
||||
{
|
||||
if (Player.Owner && col.gameObject == Player.Owner.gameObject)
|
||||
if (Player.Instance && col.gameObject == Player.Instance.gameObject)
|
||||
{
|
||||
Debug.Log("Player triggered springboard");
|
||||
Player.Owner.AddExtraForce(Vector3.up * _force, true, _duration, _curve);
|
||||
//Player.Instance.AddExtraForce(transform.up * _force, true, _duration, _curve);
|
||||
_onJump?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user