-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlayer.cs
320 lines (276 loc) · 13.1 KB
/
Player.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
using BeardedManStudios.Forge.Networking.Generated;
using System;
using System.Linq;
using ProjectSL.Util;
using UnityEngine;
namespace AuthMovementExample
{
/// <summary>
/// The networked component of the Player object
/// Handles all communications over the network
/// and updating of the entity's state
/// </summary>
public class Player : PlayerBehavior
{
#region Inspector
[Tooltip("The movement speed of the player.")]
public float Speed = 1.0f;
[Tooltip("Sibling MonoBehavior representing the view.")]
public GameObject View;
#endregion
private Rigidbody _rigidBody;
//private Rigidbody2D _rigidBody;
//private Collider2D _collider2D;
//private ContactFilter2D _noFilter;
//private readonly Collider2D[] _collisions = new Collider2D[20];
private bool _networkReady;
private bool _initialized;
private bool _isLocalOwner;
private InputFrame _currentInput;
private InputListener _inputListener;
// Last frame that was processed locally on this machine
private uint _lastLocalFrame;
// Last frame that was sent (server)/received (client) on the network
private uint _lastNetworkFrame;
// Calculates the current error between the Simulation and View
private Vector3 _errorVector = Vector3.zero; // DKE Changed from Vector2 to Vector3
// The interpolation timer for error interpolation
private float _errorTimer;
private void Awake()
{
_rigidBody = GetComponentInChildren<Rigidbody>();
//_collider2D = GetComponentInChildren<Collider2D>();
//_noFilter = new ContactFilter2D().NoFilter();
}
protected override void NetworkStart()
{
base.NetworkStart();
_networkReady = true;
}
/// <summary>
/// Initialization method, sets all the initial parameters
/// </summary>
/// <returns></returns>
private bool Initialize()
{
if (!networkObject.IsServer)
{
if (networkObject.ownerNetId == 0)
{
_initialized = false;
return _initialized;
}
}
_isLocalOwner = networkObject.MyPlayerId == networkObject.ownerNetId;
if (_isLocalOwner || networkObject.IsServer)
{
networkObject.positionInterpolation.Enabled = false;
if (_inputListener == null)
{
_inputListener = FindObjectsOfType<InputListener>()
.FirstOrDefault(x => x.networkObject.Owner.NetworkId == networkObject.ownerNetId);
if (_inputListener == null)
{
_initialized = false;
return _initialized;
}
}
}
_initialized = true;
return _initialized;
}
/// <summary>
/// Unity's Update method.
/// Handles network synchronization and Update of EntityState
/// </summary>
private void Update()
{
if (!_networkReady || !_initialized) return;
// Set the networked fields in Update so we are
// up to date per the last physics update
if (networkObject.IsServer)
{
if (_lastNetworkFrame < _lastLocalFrame)
{
networkObject.position = _rigidBody.position;
networkObject.rotation = _rigidBody.rotation; // Added DKE
_lastNetworkFrame = _lastLocalFrame;
networkObject.frame = _lastLocalFrame;
}
}
// The local player has to smooth away some error
else if (_isLocalOwner)
{
CorrectError();
}
// Update frame numbers and authoritatively set position if It's a remote player
else
{
_lastLocalFrame = _lastNetworkFrame = networkObject.frame;
View.transform.position = new Vector3(_rigidBody.position.x, _rigidBody.position.y, View.transform.position.z);
}
}
/// <summary>
/// Unity's FixedUpdate method
/// Handles prediction, server processing, reconciliation
/// & FixedUpdate of state
/// </summary>
void FixedUpdate()
{
// Don't start until initialization is done, stop updating if the input is lost
if (!_networkReady) return;
if (!_initialized && !Initialize()) return;
if ((networkObject.IsServer || _isLocalOwner) && _inputListener == null) return;
#region Netcode Logic
// Server Authority - snap the position on all clients to the server's position
if (!networkObject.IsServer)
{
_rigidBody.position = networkObject.position;
_rigidBody.rotation = networkObject.rotation; // Added DKE
if (_isLocalOwner && networkObject.frame != 0 && _lastNetworkFrame <= networkObject.frame)
{
_lastNetworkFrame = networkObject.frame;
Reconcile();
}
}
if (!_isLocalOwner && !networkObject.IsServer) return;
// Local client prediction & server authoritative logic
if (_inputListener.FramesToPlay.Count <= 0) return;
_currentInput = _inputListener.FramesToPlay.Pop();
_lastLocalFrame = _currentInput.frameNumber;
// Try to do a player update (if this fails, something's weird)
try
{
PlayerUpdate(_currentInput);
}
catch (Exception e)
{
Debug.LogError("Malformed input frame.");
Debug.LogError(e);
}
_inputListener.FramesToReconcile.Add(_currentInput);
#endregion
}
/// <summary>
/// Move the player's simulation (rigid body)
/// </summary>
/// <param name="input"></param>
private void Move(InputFrame input)
{
// Move the player, clamping the movement so diagonals aren't faster
//Vector2 translation =
// Vector2.ClampMagnitude(new Vector2(input.horizontal, input.vertical) * Speed * Time.fixedDeltaTime,
// Speed);
//_rigidBody.position += translation;
//_rigidBody.velocity = translation;
_rigidBody.velocity = new Vector2(input.horizontal, input.vertical) * Speed * Time.fixedDeltaTime;
_rigidBody.position += _rigidBody.velocity;
}
// DKE: Added MoveTank
private void MoveTank(InputFrame input)
{
// Create a vector in the direction the tank is facing with a magnitude based on the input, speed and the time between frames.
Vector3 movement = transform.forward * input.vertical * 5 * Time.deltaTime;
// Apply this movement to the rigidbody's position.
_rigidBody.MovePosition(_rigidBody.position + movement);
}
// DKE: Added TurnTank
private void TurnTank(InputFrame input)
{
// Determine the number of degrees to be turned based on the input, speed and time between frames.
float turn = input.horizontal * 40 * Time.deltaTime;
// Make this into a rotation in the y axis.
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
// Apply this rotation to the rigidbody's rotation.
_rigidBody.MoveRotation(_rigidBody.rotation * turnRotation);
}
/// <summary>
/// Detect and resolve collisions with a simple overlap check
/// </summary>
private void PhysicsCollisions()
{
/*
// We don't want to be pushed if we aren't moving.
if (_rigidBody.velocity == Vector2.zero) return;
// Collision detection - get a list of colliders the player's collider overlaps with
int numColliders = Physics2D.OverlapCollider(_collider2D, _noFilter, _collisions);
// Collision Resolution - for each of these colliders check if that collider and the player overlap
for (int i = 0; i < numColliders; ++i)
{
ColliderDistance2D overlap = _collider2D.Distance(_collisions[i]);
// If the colliders overlap move the player
if (overlap.isOverlapped) _rigidBody.position += overlap.normal * overlap.distance;
}
*/
}
/// <summary>
/// Player update composed of movement and collision processing
/// </summary>
/// <param name="input"></param>
private void PlayerUpdate(InputFrame input)
{
// Set the velocity to zero, move the player based on the next input, then detect & resolve collisions
_rigidBody.velocity = Vector3.zero; // DKE Changed Vector2 to Vector3
if (input != null && input.HasInput)
{
//Debug.Log("PlayerUpdate has input");
//Move(input); // DKE: removed
MoveTank(input); // DKE: Replaced Move by MoveTank + TurnTank
TurnTank(input); // DKE: added
PhysicsCollisions();
}
}
/// <summary>
/// Reconcile inputs that haven't yet been
/// authoritatively processed by the server
/// </summary>
private void Reconcile()
{
// Remove any inputs up to and including the last input processed by the server
_inputListener.FramesToReconcile.RemoveAll(f => f.frameNumber < networkObject.frame);
// Replay them all back to the last input processed by client prediction
if (_inputListener.FramesToReconcile.Count > 0)
{
for (Int32 i = 0; i < _inputListener.FramesToReconcile.Count; ++i)
{
_currentInput = _inputListener.FramesToReconcile[i];
PlayerUpdate(_currentInput);
}
}
// The error vector measures the difference between the predicted & server updated sim position (this one)
// and the view position (the position of the MonoBehavior holding your renderer/view)
_errorVector = _rigidBody.position - (Vector3)View.transform.position; // Changed Vector 2 into 3
_errorTimer = 0.0f;
}
/// <summary>
/// Interpolate away errors between the simulation
/// and render positions of the entity over time
/// </summary>
private void CorrectError()
{
// If we have a measurable error
if (_errorVector.magnitude >= 0.00001f)
{
// Determine the weight, or amount we interpolate towards the simulation position
float weight = Math.Max(0.0f, 0.75f - _errorTimer);
// Interpolate towards the simulation position
Vector3 newViewPosition = (Vector3)View.transform.position * weight + _rigidBody.position * (1.0f - weight); // Changed Vector 2 into 3
View.transform.position = new Vector3(newViewPosition.x, newViewPosition.y, View.transform.position.z);
// Increase the timer - makes the weight smaller meaning more weight towards the simulation position
// This is so that the bigger the error gets, or the longer it takes to smooth,
// the more is smoothed away on the next frame
_errorTimer += Time.fixedDeltaTime;
// New error vector, always the difference between sim and view
_errorVector = _rigidBody.position - (Vector3)View.transform.position; // Changed Vector 2 into 3
// If the error is REALLY small we can discount the rest
if (!(_errorVector.magnitude < 0.00001f)) return;
_errorVector = Vector3.zero; // Changed Vector 2 into 3
_errorTimer = 0.0f;
}
else
{
View.transform.position = new Vector3(_rigidBody.position.x, _rigidBody.position.y, View.transform.position.z);
}
}
}
}