-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathconnection.ts
71 lines (58 loc) · 2.15 KB
/
connection.ts
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
//
// IMPORTANT :
// - include `noLib: false` to your tsconfig.json file, under "compilerOptions"
//
///<reference lib="es2015.symbol" />
///<reference lib="es2015.symbol.wellknown" />
///<reference lib="es2015.collection" />
///<reference lib="es2015.iterable" />
import { Client, Room } from "colyseus.js";
import { isPreviewMode, getCurrentRealm } from '@decentraland/EnvironmentAPI'
import { getUserData } from "@decentraland/Identity";
export async function connect(roomName: string, options: any = {}) {
const isPreview = await isPreviewMode();
const realm = await getCurrentRealm();
//
// make sure users are matched together by the same "realm".
//
options.realm = realm?.displayName;
options.userData = await getUserData();
log("userData:", options.userData);
// const ENDPOINT = "wss://hept-j.colyseus.dev";
const ENDPOINT = (isPreview)
? "ws://127.0.0.1:2567" // local environment
: "wss://hept-j.colyseus.dev"; // production environment
if (isPreview) { addConnectionDebugger(ENDPOINT); }
const client = new Client(ENDPOINT);
try {
//
// Docs: https://docs.colyseus.io/client/client/#joinorcreate-roomname-string-options-any
//
const room = await client.joinOrCreate<any>(roomName, options);
if (isPreview) { updateConnectionDebugger(room); }
return room;
} catch (e) {
updateConnectionMessage(`Error: ${e.message}`, Color4.Red())
throw e;
}
}
let message: UIText;
function addConnectionDebugger(endpoint: string) {
const canvas = new UICanvas()
message = new UIText(canvas)
message.fontSize = 15
message.width = 120
message.height = 30
message.hTextAlign = "center";
message.vAlign = "bottom"
message.positionX = -80
updateConnectionMessage(`Connecting to ${endpoint}`, Color4.White());
}
function updateConnectionMessage(value: string, color: Color4) {
message.value = value;
message.color = color;
}
function updateConnectionDebugger(room: Room) {
updateConnectionMessage("Connected.", Color4.Green());
room.onLeave(() => updateConnectionMessage("Connection lost", Color4.Red()));
}