forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameClient.cs
More file actions
98 lines (77 loc) · 2.56 KB
/
GameClient.cs
File metadata and controls
98 lines (77 loc) · 2.56 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
using UnityEngine;
using LiteNetLib;
using LiteNetLib.Utils;
public class GameClient : MonoBehaviour, INetEventListener
{
private NetManager _netClient;
[SerializeField] private GameObject _clientBall;
[SerializeField] private GameObject _clientBallInterpolated;
private float _newBallPosX;
private float _oldBallPosX;
private float _lerpTime;
void Start()
{
_netClient = new NetManager(this);
_netClient.Start();
_netClient.UpdateTime = 15;
}
void Update()
{
_netClient.PollEvents();
var peer = _netClient.GetFirstPeer();
if (peer != null && peer.ConnectionState == ConnectionState.Connected)
{
//Fixed delta set to 0.05
var pos = _clientBallInterpolated.transform.position;
pos.x = Mathf.Lerp(_oldBallPosX, _newBallPosX, _lerpTime);
_clientBallInterpolated.transform.position = pos;
//Basic lerp
_lerpTime += Time.deltaTime / Time.fixedDeltaTime;
}
else
{
_netClient.SendDiscoveryRequest(new byte[] {1}, 5000);
}
}
void OnDestroy()
{
if (_netClient != null)
_netClient.Stop();
}
public void OnPeerConnected(NetPeer peer)
{
Debug.Log("[CLIENT] We connected to " + peer.EndPoint);
}
public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode)
{
Debug.Log("[CLIENT] We received error " + socketErrorCode);
}
public void OnNetworkReceive(NetPeer peer, NetDataReader reader, DeliveryMethod deliveryMethod)
{
_newBallPosX = reader.GetFloat();
var pos = _clientBall.transform.position;
_oldBallPosX = pos.x;
pos.x = _newBallPosX;
_clientBall.transform.position = pos;
_lerpTime = 0f;
}
public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader,
UnconnectedMessageType messageType)
{
if (messageType == UnconnectedMessageType.DiscoveryResponse && _netClient.PeersCount == 0)
{
Debug.Log("[CLIENT] Received discovery response. Connecting to: " + remoteEndPoint);
_netClient.Connect(remoteEndPoint, "sample_app");
}
}
public void OnNetworkLatencyUpdate(NetPeer peer, int latency)
{
}
public void OnConnectionRequest(ConnectionRequest request)
{
}
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
Debug.Log("[CLIENT] We disconnected because " + disconnectInfo.Reason);
}
}