-
Notifications
You must be signed in to change notification settings - Fork 0
/
ColyseusClient.cs
275 lines (221 loc) · 6.62 KB
/
ColyseusClient.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
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
using System.Collections.Generic;
using System;
using Colyseus;
using GameDevWare.Serialization;
using GameDevWare.Serialization.MessagePack;
public class ColyseusClient : MonoBehaviour {
public Client client;
public Room room;
public string serverName = "localhost";
public string port = "2657";
public string roomName = "hub";
public GameObject myPlayer;
public Spawner spawner;
WaitForSeconds waitForSeconds = new WaitForSeconds(1f);
public delegate void OnDeleyedTimeChange(DataChange change);
public event OnDeleyedTimeChange onDeleyedTimeChange;
// Use this for initialization
IEnumerator Start () {
String uri = "ws://" + serverName + ":" + port;
client = new Client(uri);
client.OnOpen += OnOpenHandler;
client.OnClose += (object sender, EventArgs e) => Debug.Log ("CONNECTION CLOSED");
yield return StartCoroutine(client.Connect());
room = client.Join(roomName);
room.OnReadyToConnect += (sender, e) => StartCoroutine ( room.Connect() );
room.OnJoin += OnRoomJoined;
room.OnStateChange += OnUpdateHandler;
room.OnError += (sender, e) =>
{
Debug.Log("oops, error ocurred:");
Debug.Log(e);
};
room.Listen("players/:id", OnPlayerChange);
room.Listen ("players/:id/moveTo/:axis", this.OnPlayerMove);
room.Listen("teams/:id", OnTeamChange);
room.Listen ("elapsedTime", OnElapsedTimeChange);
room.Listen (this.OnChangeFallback);
room.OnMessage += OnData;
StartCoroutine("SendMyPlayerPosition");
while (true)
{
client.Recv();
yield return 0;
}
}
IEnumerator SendMyPlayerPosition() {
while (true)
{
// Place your method calls
if (room.sessionId != null) {
Debug.Log ("SET_PLAYER_POSITION");
var playerPosition = myPlayer.transform.position;
room.Send (new {
action = "SET_PLAYER_POSITION",
payload = new {
x = playerPosition.x,
y = playerPosition.y,
z = playerPosition.z
}
});
}
yield return waitForSeconds;
}
}
void OnDestroy ()
{
// Make sure client will disconnect from the server
room.Leave ();
client.Close ();
}
void OnOpenHandler (object sender, EventArgs e)
{
Debug.Log("Connected to server. Client id: " + client.id);
}
void OnRoomJoined (object sender, EventArgs e)
{
Debug.Log("Joined room successfully.");
//SendMoveTo (new Vector3(10,0,10));
}
void OnData (object sender, MessageEventArgs e)
{
var data = (IndexedDictionary<string, object>) e.message;
if((data["action"] as string == "MOVE_PLAYER_TO") && (data["playerId"] as string != room.sessionId)) {
var player = spawner.PlayerFindById (data ["playerId"] as string);
var agent = player.GetComponent<UnityEngine.AI.NavMeshAgent>();
var x = data ["x"];
var y = data ["y"];
var z = data ["z"];
var destinationX = float.Parse (x as string);
var destinationY = float.Parse (y as string);
var destinationZ = float.Parse (z as string);
var destination = new Vector3 (destinationX, destinationY, destinationZ);
agent.SetDestination(destination);
}
}
void OnUpdateHandler (object sender, RoomUpdateEventArgs e)
{
// Setup room first state
if (e.isFirstState) {
IndexedDictionary<string, object> players = (IndexedDictionary<string, object>) e.state ["players"];
// trigger to add existing players
/*
foreach(KeyValuePair<string, object> player in players)
{
this.OnPlayerChange (new DataChange {
path = new Dictionary<string, string> {
{"id", player.Key}
},
operation = "add",
value = player.Value
});
}
*/
}
}
void OnElapsedTimeChange (DataChange change)
{
onDeleyedTimeChange(change);
}
void OnPlayerChange (DataChange change)
{
Debug.Log ("OnPlayerChange");
Debug.Log (change.operation);
Debug.Log (change.path["id"]);
Debug.Log (change.value);
var data = (IndexedDictionary<string, object>) change.value;
if (change.operation == "add") {
if (change.path ["id"] == room.sessionId) {
spawner.PlayerAdd (change.path ["id"], myPlayer);
NavMeshAgent agent = myPlayer.GetComponent<NavMeshAgent> ();
agent.enabled = false;
Transform transform = myPlayer.GetComponent<Transform> ();
var currentPosition = (IndexedDictionary<string, object>) data["currentPosition"];
var x = Convert.ToSingle (currentPosition ["x"]);
var y = Convert.ToSingle (currentPosition ["y"]);
var z = Convert.ToSingle (currentPosition ["z"]);
transform.SetPositionAndRotation (new Vector3 (x, y, z), transform.rotation);
agent.enabled = true;
Debug.Log ("My Player Added");
} else {
var currentPosition = (IndexedDictionary<string, object>) data["currentPosition"];
var x = Convert.ToSingle (currentPosition ["x"]);
var y = Convert.ToSingle (currentPosition ["y"]);
var z = Convert.ToSingle (currentPosition ["z"]);
spawner.PlayerSpawn (change.path ["id"], new Vector3(x, y, z));
Debug.Log ("Other Player Added");
}
} else if (change.operation == "remove") {
spawner.PlayerRemove (change.path ["id"]);
Debug.Log ("Player removed");
}
}
void OnPlayerMove (DataChange change)
{
/*
Debug.Log ("ON_PLAYER_MOVED");
var x = change.path;
var y = x ["axis"];
Debug.Log ("playerId: " + change.path["id"] + ", Axis: " + change.path["axis"]);
Debug.Log (change);
Debug.Log (change.value);
*/
/*
GameObject cube;
players.TryGetValue (change.path ["id"], out cube);
cube.transform.Translate (new Vector3 (Convert.ToSingle(change.value), 0, 0));
*/
}
void OnPlayerRemoved (DataChange change)
{
Debug.Log ("OnPlayerRemoved");
Debug.Log (change.path);
Debug.Log (change.value);
}
void OnTeamChange (DataChange change)
{
/*
Debug.Log ("OnTeamChange");
Debug.Log (change.operation);
Debug.Log (change.path["id"]);
Debug.Log (change.value);
if (change.operation == "add") {
Debug.Log ("Team added");
} else if (change.operation == "remove") {
Debug.Log ("Team removed");
}
*/
}
void OnMessageAdded (DataChange change)
{
Debug.Log ("OnMessageAdded");
Debug.Log (change.path["number"]);
Debug.Log (change.value);
}
void OnChangeFallback (PatchObject change)
{
// Debug.Log ("OnChangeFallback");
// Debug.Log (change.operation);
// Debug.Log (change.path);
// Debug.Log (change.value);
}
void OnApplicationQuit()
{
// Ensure the connection with server is closed immediatelly
room.Leave();
client.Close();
}
public void SendMoveTo(Vector3 destination) {
room.Send (new {
action = "MOVE_PLAYER_TO",
payload = new {
x = destination.x,
y = destination.y,
z = destination.z
}
});
}
}