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
99 lines (78 loc) · 2.65 KB
/
GameClient.cs
File metadata and controls
99 lines (78 loc) · 2.65 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
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using LiteNetLib;
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.UnconnectedMessagesEnabled = true;
_netClient.UpdateTime = 15;
_netClient.Start();
}
void Update()
{
_netClient.PollEvents();
var peer = _netClient.FirstPeer;
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.SendBroadcast(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(IPEndPoint endPoint, SocketError socketErrorCode)
{
Debug.Log("[CLIENT] We received error " + socketErrorCode);
}
public void OnNetworkReceive(NetPeer peer, NetPacketReader 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(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
{
if (messageType == UnconnectedMessageType.BasicMessage && _netClient.PeersCount == 0 && reader.GetInt() == 1)
{
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);
}
}