-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathCPMPlayer.cs
380 lines (317 loc) · 11.9 KB
/
CPMPlayer.cs
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
* - Edited by PrzemyslawNowaczyk (11.10.17)
* -----------------------------
* Deleting unused variables
* Changing obsolete methods
* Changing used input methods for consistency
* -----------------------------
*
* - Edited by NovaSurfer (31.01.17).
* -----------------------------
* Rewriting from JS to C#
* Deleting "Spawn" and "Explode" methods, deleting unused varibles
* -----------------------------
* Just some side notes here.
*
* - Should keep in mind that idTech's cartisian plane is different to Unity's:
* Z axis in idTech is "up/down" but in Unity Z is the local equivalent to
* "forward/backward" and Y in Unity is considered "up/down".
*
* - Code's mostly ported on a 1 to 1 basis, so some naming convensions are a
* bit fucked up right now.
*
* - UPS is measured in Unity units, the idTech units DO NOT scale right now.
*
* - Default values are accurate and emulates Quake 3's feel with CPM(A) physics.
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Contains the command the user wishes upon the character
struct Cmd
{
public float forwardMove;
public float rightMove;
public float upMove;
}
public class CPMPlayer : MonoBehaviour
{
public Transform playerView; // Camera
public float playerViewYOffset = 0.6f; // The height at which the camera is bound to
public float xMouseSensitivity = 30.0f;
public float yMouseSensitivity = 30.0f;
//
/*Frame occuring factors*/
public float gravity = 20.0f;
public float friction = 6; //Ground friction
/* Movement stuff */
public float moveSpeed = 7.0f; // Ground move speed
public float runAcceleration = 14.0f; // Ground accel
public float runDeacceleration = 10.0f; // Deacceleration that occurs when running on the ground
public float airAcceleration = 2.0f; // Air accel
public float airDecceleration = 2.0f; // Deacceleration experienced when ooposite strafing
public float airControl = 0.3f; // How precise air control is
public float sideStrafeAcceleration = 50.0f; // How fast acceleration occurs to get up to sideStrafeSpeed when
public float sideStrafeSpeed = 1.0f; // What the max speed to generate when side strafing
public float jumpSpeed = 8.0f; // The speed at which the character's up axis gains when hitting jump
public bool holdJumpToBhop = false; // When enabled allows player to just hold jump button to keep on bhopping perfectly. Beware: smells like casual.
/*print() style */
public GUIStyle style;
/*FPS Stuff */
public float fpsDisplayRate = 4.0f; // 4 updates per sec
private int frameCount = 0;
private float dt = 0.0f;
private float fps = 0.0f;
private CharacterController _controller;
// Camera rotations
private float rotX = 0.0f;
private float rotY = 0.0f;
private Vector3 moveDirectionNorm = Vector3.zero;
private Vector3 playerVelocity = Vector3.zero;
private float playerTopVelocity = 0.0f;
// Q3: players can queue the next jump just before he hits the ground
private bool wishJump = false;
// Used to display real time fricton values
private float playerFriction = 0.0f;
// Player commands, stores wish commands that the player asks for (Forward, back, jump, etc)
private Cmd _cmd;
private void Start()
{
// Hide the cursor
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
if (playerView == null)
{
Camera mainCamera = Camera.main;
if (mainCamera != null)
playerView = mainCamera.gameObject.transform;
}
// Put the camera inside the capsule collider
playerView.position = new Vector3(
transform.position.x,
transform.position.y + playerViewYOffset,
transform.position.z);
_controller = GetComponent<CharacterController>();
}
private void Update()
{
// Do FPS calculation
frameCount++;
dt += Time.deltaTime;
if (dt > 1.0 / fpsDisplayRate)
{
fps = Mathf.Round(frameCount / dt);
frameCount = 0;
dt -= 1.0f / fpsDisplayRate;
}
/* Ensure that the cursor is locked into the screen */
if (Cursor.lockState != CursorLockMode.Locked) {
if (Input.GetButtonDown("Fire1"))
Cursor.lockState = CursorLockMode.Locked;
}
/* Camera rotation stuff, mouse controls this shit */
rotX -= Input.GetAxisRaw("Mouse Y") * xMouseSensitivity * 0.02f;
rotY += Input.GetAxisRaw("Mouse X") * yMouseSensitivity * 0.02f;
// Clamp the X rotation
if(rotX < -90)
rotX = -90;
else if(rotX > 90)
rotX = 90;
this.transform.rotation = Quaternion.Euler(0, rotY, 0); // Rotates the collider
playerView.rotation = Quaternion.Euler(rotX, rotY, 0); // Rotates the camera
/* Movement, here's the important part */
QueueJump();
if(_controller.isGrounded)
GroundMove();
else if(!_controller.isGrounded)
AirMove();
// Move the controller
_controller.Move(playerVelocity * Time.deltaTime);
/* Calculate top velocity */
Vector3 udp = playerVelocity;
udp.y = 0.0f;
if(udp.magnitude > playerTopVelocity)
playerTopVelocity = udp.magnitude;
//Need to move the camera after the player has been moved because otherwise the camera will clip the player if going fast enough and will always be 1 frame behind.
// Set the camera's position to the transform
playerView.position = new Vector3(
transform.position.x,
transform.position.y + playerViewYOffset,
transform.position.z);
}
/*******************************************************************************************************\
|* MOVEMENT
\*******************************************************************************************************/
/**
* Sets the movement direction based on player input
*/
private void SetMovementDir()
{
_cmd.forwardMove = Input.GetAxisRaw("Vertical");
_cmd.rightMove = Input.GetAxisRaw("Horizontal");
}
/**
* Queues the next jump just like in Q3
*/
private void QueueJump()
{
if(holdJumpToBhop)
{
wishJump = Input.GetButton("Jump");
return;
}
if(Input.GetButtonDown("Jump") && !wishJump)
wishJump = true;
if(Input.GetButtonUp("Jump"))
wishJump = false;
}
/**
* Execs when the player is in the air
*/
private void AirMove()
{
Vector3 wishdir;
float wishvel = airAcceleration;
float accel;
SetMovementDir();
wishdir = new Vector3(_cmd.rightMove, 0, _cmd.forwardMove);
wishdir = transform.TransformDirection(wishdir);
float wishspeed = wishdir.magnitude;
wishspeed *= moveSpeed;
wishdir.Normalize();
moveDirectionNorm = wishdir;
// CPM: Aircontrol
float wishspeed2 = wishspeed;
if (Vector3.Dot(playerVelocity, wishdir) < 0)
accel = airDecceleration;
else
accel = airAcceleration;
// If the player is ONLY strafing left or right
if(_cmd.forwardMove == 0 && _cmd.rightMove != 0)
{
if(wishspeed > sideStrafeSpeed)
wishspeed = sideStrafeSpeed;
accel = sideStrafeAcceleration;
}
Accelerate(wishdir, wishspeed, accel);
if(airControl > 0)
AirControl(wishdir, wishspeed2);
// !CPM: Aircontrol
// Apply gravity
playerVelocity.y -= gravity * Time.deltaTime;
}
/**
* Air control occurs when the player is in the air, it allows
* players to move side to side much faster rather than being
* 'sluggish' when it comes to cornering.
*/
private void AirControl(Vector3 wishdir, float wishspeed)
{
float zspeed;
float speed;
float dot;
float k;
// Can't control movement if not moving forward or backward
if(Mathf.Abs(_cmd.forwardMove) < 0.001 || Mathf.Abs(wishspeed) < 0.001)
return;
zspeed = playerVelocity.y;
playerVelocity.y = 0;
/* Next two lines are equivalent to idTech's VectorNormalize() */
speed = playerVelocity.magnitude;
playerVelocity.Normalize();
dot = Vector3.Dot(playerVelocity, wishdir);
k = 32;
k *= airControl * dot * dot * Time.deltaTime;
// Change direction while slowing down
if (dot > 0)
{
playerVelocity.x = playerVelocity.x * speed + wishdir.x * k;
playerVelocity.y = playerVelocity.y * speed + wishdir.y * k;
playerVelocity.z = playerVelocity.z * speed + wishdir.z * k;
playerVelocity.Normalize();
moveDirectionNorm = playerVelocity;
}
playerVelocity.x *= speed;
playerVelocity.y = zspeed; // Note this line
playerVelocity.z *= speed;
}
/**
* Called every frame when the engine detects that the player is on the ground
*/
private void GroundMove()
{
Vector3 wishdir;
// Do not apply friction if the player is queueing up the next jump
if (!wishJump)
ApplyFriction(1.0f);
else
ApplyFriction(0);
SetMovementDir();
wishdir = new Vector3(_cmd.rightMove, 0, _cmd.forwardMove);
wishdir = transform.TransformDirection(wishdir);
wishdir.Normalize();
moveDirectionNorm = wishdir;
var wishspeed = wishdir.magnitude;
wishspeed *= moveSpeed;
Accelerate(wishdir, wishspeed, runAcceleration);
// Reset the gravity velocity
playerVelocity.y = -gravity * Time.deltaTime;
if(wishJump)
{
playerVelocity.y = jumpSpeed;
wishJump = false;
}
}
/**
* Applies friction to the player, called in both the air and on the ground
*/
private void ApplyFriction(float t)
{
Vector3 vec = playerVelocity; // Equivalent to: VectorCopy();
float speed;
float newspeed;
float control;
float drop;
vec.y = 0.0f;
speed = vec.magnitude;
drop = 0.0f;
/* Only if the player is on the ground then apply friction */
if(_controller.isGrounded)
{
control = speed < runDeacceleration ? runDeacceleration : speed;
drop = control * friction * Time.deltaTime * t;
}
newspeed = speed - drop;
playerFriction = newspeed;
if(newspeed < 0)
newspeed = 0;
if(speed > 0)
newspeed /= speed;
playerVelocity.x *= newspeed;
playerVelocity.z *= newspeed;
}
private void Accelerate(Vector3 wishdir, float wishspeed, float accel)
{
float addspeed;
float accelspeed;
float currentspeed;
currentspeed = Vector3.Dot(playerVelocity, wishdir);
addspeed = wishspeed - currentspeed;
if(addspeed <= 0)
return;
accelspeed = accel * Time.deltaTime * wishspeed;
if(accelspeed > addspeed)
accelspeed = addspeed;
playerVelocity.x += accelspeed * wishdir.x;
playerVelocity.z += accelspeed * wishdir.z;
}
private void OnGUI()
{
GUI.Label(new Rect(0, 0, 400, 100), "FPS: " + fps, style);
var ups = _controller.velocity;
ups.y = 0;
GUI.Label(new Rect(0, 15, 400, 100), "Speed: " + Mathf.Round(ups.magnitude * 100) / 100 + "ups", style);
GUI.Label(new Rect(0, 30, 400, 100), "Top Speed: " + Mathf.Round(playerTopVelocity * 100) / 100 + "ups", style);
}
}