aboutsummaryrefslogtreecommitdiff
path: root/static/src/main.ts
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-08-24 19:11:26 -0700
committerElizabeth Hunt <elizabeth.hunt@simponic.xyz>2024-08-24 19:16:22 -0700
commita0a2068b66204d7d06eb3c3b4aa61b28469121f6 (patch)
treee9706970af1ce8b4d12df9c0a3f64fa17ca74b97 /static/src/main.ts
parentb144ad5df76e458297bd6dc030cad4af0f344901 (diff)
downloadkennel.hatecomputers.club-a0a2068b66204d7d06eb3c3b4aa61b28469121f6.tar.gz
kennel.hatecomputers.club-a0a2068b66204d7d06eb3c3b4aa61b28469121f6.zip
improve event parsing and begin sending events from the client
Diffstat (limited to 'static/src/main.ts')
-rw-r--r--static/src/main.ts47
1 files changed, 40 insertions, 7 deletions
diff --git a/static/src/main.ts b/static/src/main.ts
index 8d12587..fc04b72 100644
--- a/static/src/main.ts
+++ b/static/src/main.ts
@@ -1,18 +1,51 @@
import $ from "jquery";
+import { Vec2 } from "./vector";
+import { EventType, type SetControllableEvent, type Event } from "./event";
+import { MouseController } from "./mouse_controller";
$(document).ready(async () => {
- await fetch("/assign", {
+ const session_id = await fetch("/assign", {
credentials: "include",
+ })
+ .then((res) => res.json())
+ .then(({ session }) => session);
+
+ const controllable_entities = new Set<string>();
+ const control_callback = (movement: Vec2) => {
+ for (const id of controllable_entities) {
+ const message = JSON.stringify({
+ event_type: EventType.ENTITY_POSITION_UPDATE,
+ data: { id, position: movement },
+ });
+ ws.send(message);
+ }
+ };
+ const mouse_controller = new MouseController(control_callback);
+ $(document).on("mousemove", (event) => {
+ mouse_controller.move(event.clientX, event.clientY);
});
+ mouse_controller.start();
const ws = new WebSocket("/ws");
- ws.onopen = () => {
- console.log("connected");
- };
+ await new Promise<void>((resolve) => {
+ ws.onopen = () => {
+ console.log("connected");
+ resolve();
+ };
+ });
ws.onmessage = ({ data }) => {
- console.log(JSON.parse(data));
+ const [event_type, event_data] = JSON.parse(data);
+ const message = { event_type, data: event_data } as Event;
+
+ console.log("Received message", message);
+ if (message.event_type === EventType.SET_CONTROLLABLE) {
+ const event = message as SetControllableEvent;
+ if (event.data.client_id === session_id) {
+ controllable_entities.add(event.data.id);
+ }
+ }
};
- ws.onclose = (e) => {
- console.log("disconnected", e);
+ ws.onclose = () => {
+ controllable_entities.clear();
};
});