diff --git a/src/hooks/useSocket.ts b/src/hooks/useSocket.ts new file mode 100644 index 0000000..a68b19b --- /dev/null +++ b/src/hooks/useSocket.ts @@ -0,0 +1,24 @@ +import { useEffect } from "react"; +import { useSocketRefStore } from "../store"; +import { PointerSchema, ActionSchema, HitSchema } from "../type/shooting"; + +export const useSocketReciever = () => { + const socketRef = useSocketRefStore((state) => state.socketRef); + + const onMessage = (handler: (data: (PointerSchema | ActionSchema | HitSchema)) => void) => { + useEffect(() => { + const onMessage = (event: MessageEvent) => { + const data = JSON.parse(event.data); + handler(data); + }; + + const currentSocketRef = socketRef?.current; + currentSocketRef?.addEventListener("message", onMessage); + return () => { + currentSocketRef?.removeEventListener("message", onMessage); + }; + }, [socketRef, handler]); + }; + + return { onMessage }; +}; diff --git a/src/pages/shooter/index.tsx b/src/pages/shooter/index.tsx index 949144d..1ca4f07 100644 --- a/src/pages/shooter/index.tsx +++ b/src/pages/shooter/index.tsx @@ -11,10 +11,13 @@ import { useOrientation } from "../../hooks/useOrientation"; import { useSocketRefStore, useUUIDStore } from "../../store"; import { type Schema, event_type, message_type } from "../../type/schema"; import style from "./index.module.css"; +import { useSocketReciever } from "../../hooks/useSocket"; const Shooter = () => { const [isOpen, setIsOpen] = useState(true); + const [score, setScore] = useState(0); const { orientationDiff } = useOrientation(); + const { onMessage } = useSocketReciever(); const socketRef = useSocketRefStore((state) => state.socketRef); const initialImages = [ @@ -68,6 +71,15 @@ const Shooter = () => { }; }, [sendData]); + useEffect(() => { + onMessage((data) => { + if (data.id === uuid) { + setScore((prevScore) => prevScore + 1); + console.debug(score); + } + }); + }, [onMessage]) + const handleClick = () => { const audio = new Audio("/sound/cork_sound.mp3"); audio diff --git a/src/type/shooting.ts b/src/type/shooting.ts index f9d3a67..20e3837 100644 --- a/src/type/shooting.ts +++ b/src/type/shooting.ts @@ -1,6 +1,7 @@ export enum MessageType { Pointer = "pointer", Action = "action", + Hit = "hit", } export interface Target { @@ -26,3 +27,8 @@ export interface ActionSchema { target: Target; vector: Vector; } + +export interface HitSchema { + id: string; + message_type: MessageType.Hit; +}