-
Notifications
You must be signed in to change notification settings - Fork 551
/
Copy pathclient.ts
107 lines (91 loc) · 2.69 KB
/
client.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
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
// This is browser code that gets transformed using Parcel/Babel
// Therefore you can now use ES6 style imports
import * as Phaser from "phaser";
interface ICoords {
x: number;
y: number;
}
class GameScene extends Phaser.Scene {
private HOST = window.location.hostname; // localhost and 127.0.0.1 handled
private PORT = 8080; // change this if needed
private wsClient?: WebSocket;
private sprite?: Phaser.GameObjects.Sprite;
constructor() { super({ key: "GameScene" }); }
/**
* Load the assets required by the scene
*/
public preload() {
this.load.image("bunny", "static/bunny.png");
}
/**
* Instantiate the private variables required by the scene
*/
public init() {
// Initialize the websocket client
this.wsClient = new WebSocket(`ws://${this.HOST}:${this.PORT}`);
this.wsClient.onopen = (event) => {
// After the websocket is open, set interactivtiy
console.log(event);
// Start of the drag event (mouse click down)
this.input.on("dragstart", (
_: Phaser.Input.Pointer,
gObject: Phaser.GameObjects.Sprite
) => {
gObject.setTint(0xff0000);
});
// During the drag event (mouse movement)
this.input.on("drag", (
_: Phaser.Input.Pointer,
gObject: Phaser.GameObjects.Sprite,
dragX: number,
dragY: number
) => {
gObject.x = dragX;
gObject.y = dragY;
this.wsClient!.send(JSON.stringify({ x: gObject.x, y: gObject.y }));
});
// End of the drag event (mouse click up)
this.input.on("dragend", (
_: Phaser.Input.Pointer,
gObject: Phaser.GameObjects.Sprite
) => {
gObject.clearTint();
this.wsClient!.send(JSON.stringify({ x: gObject.x, y: gObject.y }));
});
}
this.wsClient.onmessage = (wsMsgEvent) => {
console.log(wsMsgEvent);
wsMsgEvent.data;
const actorCoordinates: ICoords = JSON.parse(wsMsgEvent.data);
// Sprite may not have been initialized yet
if (this.sprite) {
this.sprite.x = actorCoordinates.x;
this.sprite.y = actorCoordinates.y;
}
}
}
/**
* Create the game objects required by the scene
*/
public create() {
// Create an interactive, draggable bunny sprite
this.sprite = this.add.sprite(100, 100, "bunny");
this.sprite.setInteractive();
this.input.setDraggable(this.sprite);
}
}
// Phaser configuration variables
const config: GameConfig = {
type: Phaser.AUTO,
width: 800,
height: 500,
scene: [GameScene]
};
class LabDemoGame extends Phaser.Game {
constructor(config: GameConfig) {
super(config);
}
}
window.addEventListener("load", () => {
new LabDemoGame(config);
})