-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlayerMovement.cs
More file actions
214 lines (184 loc) · 7.76 KB
/
PlayerMovement.cs
File metadata and controls
214 lines (184 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using UnityEngine;
using Optimization.Core;
using Ytax.Core;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(PlayerInput))]
public class PlayerMovement : MonoBehaviour
{
// speeds
[Header("Speed")]
[SerializeField] private float walkSpeed = 2.0f;
[SerializeField] private float runSpeed = 4.0f;
[SerializeField] private float acceleration = 10.0f;
[SerializeField] private float deceleration = 15.0f;
// physics and jump
[Header("Physics & Jump")]
[SerializeField] private float gravity = -20.0f;
[SerializeField] private float jumpHeight = 1.2f;
[Range(0f, 1f)][SerializeField] private float airControl = 0.1f;
[SerializeField] private float jumpCooldown = 0.2f;
[SerializeField] private float coyoteTime = 0.1f;
[SerializeField] private float jumpBufferTime = 0.1f;
// components
private CharacterController controller;
private PlayerInput input;
private PlayerStamina stamina;
// runtime state
private Vector3 velocity;
private float currentSpeed;
private float targetSpeed;
private float jumpTimer;
private float coyoteTimer;
private float jumpBufferTimer;
// pause flag used to temporarily freeze horizontal movement e g during dialogue choices
private bool movementPaused = false;
[Range(0f, 1f)][SerializeField] private float runStrafeThreshold = 0.1f;
// public api
public Vector3 CurrentVelocity { get; private set; }
public bool IsGrounded { get; private set; }
public bool IsRunning { get; private set; }
public Vector2 CurrentInput { get; private set; }
public float WalkSpeed => walkSpeed;
public float RunSpeed => runSpeed;
public float CurrentSpeed => currentSpeed;
// unity callbacks
private void Awake()
{
controller = GetComponent<CharacterController>();
input = GetComponent<PlayerInput>();
stamina = GetComponent<PlayerStamina>();
GlobalCache.RegisterPlayer(transform);
}
private void Update()
{
ProfilerMarkers.PlayerMovement.Begin();
if (controller == null || !controller.enabled || input == null) { ProfilerMarkers.PlayerMovement.End(); return; }
if (movementPaused)
{
// while paused keep vertical physics gravity but zero horizontal movement so
// the player remains in an idle pose while animator can still run
IsGrounded = controller.isGrounded;
// zero horizontal velocity
velocity.x = 0f;
velocity.z = 0f;
// clear current input so HeadBob settles to idle instead of using stale values
CurrentInput = Vector2.zero;
// apply gravity so player can fall if in air
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
CurrentVelocity = velocity;
stamina?.SetSprinting(false, false);
return;
}
IsGrounded = controller.isGrounded;
// Normalize input to prevent faster diagonal movement
CurrentInput = Vector2.ClampMagnitude(input.Move, 1f);
float horizontal = CurrentInput.x;
float vertical = CurrentInput.y;
// only allow sprint when input asks for it and stamina permits it
bool wantsRun = input.RunHeld && vertical > 0f && Mathf.Abs(horizontal) <= runStrafeThreshold;
// Ask stamina to sprint, but then read back the authoritative state from stamina.
// This prevents using a stale local `IsRunning` value when stamina depletes later
// in the frame (execution order differences between components).
bool requestedSprint = wantsRun && (horizontal != 0f || vertical != 0f);
stamina?.SetSprinting(requestedSprint, input.RunHeld);
IsRunning = (stamina != null) ? stamina.IsSprinting : wantsRun;
if (IsGrounded)
{
coyoteTimer = coyoteTime;
// Use the stamina-backed run state to determine target speed so sprinting
// is disabled the moment stamina stops permitting it.
targetSpeed = IsRunning ? runSpeed : walkSpeed;
if (horizontal == 0f && vertical == 0f) targetSpeed = 0f;
}
else
{
coyoteTimer = Mathf.Max(0f, coyoteTimer - Time.deltaTime);
}
float accelRate = (targetSpeed > currentSpeed) ? acceleration : deceleration;
currentSpeed = Mathf.MoveTowards(currentSpeed, targetSpeed, accelRate * Time.deltaTime);
// movement math
Vector3 inputDir = Vector3.zero;
if (horizontal != 0f || vertical != 0f)
{
inputDir = (transform.right * horizontal + transform.forward * vertical).normalized;
}
if (IsGrounded)
{
Vector3 moveDir = inputDir;
// preserve momentum when stopping
if (inputDir.sqrMagnitude < 0.0001f && currentSpeed > 0.1f)
{
Vector3 horizontalVel = new Vector3(velocity.x, 0, velocity.z);
if (horizontalVel.sqrMagnitude > 0.001f)
moveDir = horizontalVel.normalized;
}
Vector3 moveVelocity = moveDir * currentSpeed;
// Prevent sliding down slopes by applying a stronger downward force when grounded
float groundStickForce = -2f;
if (inputDir.sqrMagnitude < 0.0001f)
{
groundStickForce = -10f; // Stick harder when not moving
}
velocity = new Vector3(moveVelocity.x, velocity.y < 0f ? groundStickForce : velocity.y, moveVelocity.z);
}
else
{
// physics math
if (inputDir.sqrMagnitude > 0.0001f)
{
Vector3 horizontalVel = new Vector3(velocity.x, 0f, velocity.z);
Vector3 targetVel = inputDir * Mathf.Max(horizontalVel.magnitude, walkSpeed * airControl);
Vector3 newHorizontal = Vector3.MoveTowards(horizontalVel, targetVel, walkSpeed * airControl * Time.deltaTime);
velocity.x = newHorizontal.x;
velocity.z = newHorizontal.z;
}
velocity.y += gravity * Time.deltaTime;
}
// Head bumping on ceiling
if ((controller.collisionFlags & CollisionFlags.Above) != 0 && velocity.y > 0f)
{
velocity.y = 0f;
}
if (jumpTimer > 0f) jumpTimer -= Time.deltaTime;
if (input.ConsumeJump())
{
// jump math
jumpBufferTimer = jumpBufferTime;
}
else
{
jumpBufferTimer = Mathf.Max(0f, jumpBufferTimer - Time.deltaTime);
}
bool canJump = jumpTimer <= 0f && coyoteTimer > 0f && jumpBufferTimer > 0f;
if (canJump)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
jumpTimer = jumpCooldown;
jumpBufferTimer = 0f;
coyoteTimer = 0f;
}
controller.Move(velocity * Time.deltaTime);
CurrentVelocity = velocity;
ProfilerMarkers.PlayerMovement.End();
}
/// <summary>
/// pause horizontal movement used by dialogue system while choices are shown
/// vertical physics gravity will continue so the player does not teleport
/// </summary>
public void PauseMovement()
{
movementPaused = true;
// stop horizontal velocity immediately
velocity.x = 0f;
velocity.z = 0f;
currentSpeed = 0f;
}
/// <summary>
/// resume movement after a pause
/// </summary>
public void ResumeMovement()
{
movementPaused = false;
}
}