forked from RevenantX/NetGameExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemotePlayer.cs
More file actions
76 lines (68 loc) · 2.52 KB
/
Copy pathRemotePlayer.cs
File metadata and controls
76 lines (68 loc) · 2.52 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
using Code.Shared;
using UnityEngine;
namespace Code.Client
{
public class RemotePlayer : BasePlayer
{
struct IncomingData
{
public PlayerState State;
public ushort Tick;
public IncomingData(PlayerState state, ushort serverTick)
{
State = state;
Tick = serverTick;
}
}
private readonly LiteRingBuffer<IncomingData> _buffer = new LiteRingBuffer<IncomingData>(30);
private float _receivedTime;
private float _timer;
private const float BufferTime = 0.1f; //100 milliseconds
public RemotePlayer(ClientPlayerManager manager, string name, PlayerJoinedPacket pjPacket) : base(manager, name, pjPacket.InitialPlayerState.Id)
{
_position = pjPacket.InitialPlayerState.Position;
_health = pjPacket.Health;
_rotation = pjPacket.InitialPlayerState.Rotation;
_buffer.Add(new IncomingData(pjPacket.InitialPlayerState, pjPacket.ServerTick));
}
public override void Spawn(Vector2 position)
{
_buffer.FastClear();
base.Spawn(position);
}
public void UpdatePosition(float delta)
{
if (_receivedTime < BufferTime || _buffer.Count < 2)
return;
var dataA = _buffer[0];
var dataB = _buffer[1];
float lerpTime = NetworkGeneral.SeqDiff(dataB.Tick, dataA.Tick)*LogicTimer.FixedDelta;
float t = _timer / lerpTime;
_position = Vector2.Lerp(dataA.State.Position, dataB.State.Position, t);
_rotation = Mathf.Lerp(dataA.State.Rotation, dataB.State.Rotation, t);
_timer += delta;
if (_timer > lerpTime)
{
_receivedTime -= lerpTime;
_buffer.RemoveFromStart(1);
_timer -= lerpTime;
}
}
public void OnPlayerState(ushort serverTick, PlayerState state)
{
//old command
int diff = NetworkGeneral.SeqDiff(serverTick, _buffer.Last.Tick);
if (diff <= 0)
return;
_receivedTime += diff * LogicTimer.FixedDelta;
if (_buffer.IsFull)
{
Debug.LogWarning("[C] Remote: Something happened");
//Lag?
_receivedTime = 0f;
_buffer.FastClear();
}
_buffer.Add(new IncomingData(state, serverTick));
}
}
}