From 6d7d65dc67a8939feb4adad2a9096433b44ca266 Mon Sep 17 00:00:00 2001 From: dylan <> Date: Sun, 14 May 2023 14:25:02 -0700 Subject: [PATCH] Fix mouse events --- mouse.ts | 49 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/mouse.ts b/mouse.ts index c45841a..2d3b256 100644 --- a/mouse.ts +++ b/mouse.ts @@ -13,8 +13,11 @@ const mouseButtonsDown = { [M.RIGHT]: false, [M.MIDDLE]: false, }; + +type MouseEventType = "click" | "down" | "up" | "move" | "dblclick"; + const mouseEvents: Array<{ - type: "click" | "down" | "up" | "move" | "dblclick", + type: MouseEventType, button: typeof M[keyof typeof M], x: number, y: number, @@ -27,37 +30,59 @@ let mouseY = 0; const eventPixelCoords = (evt: WindowMouseEvent) => { const {width, height} = gameWindow.size; - const pixX = Math.floor(128*evt.clientX/width); - const pixY = Math.floor(128*evt.clientY/height); + const min = Math.min(width, height); + const pixX = Math.floor(128*(evt.clientX-(width-min)/2)/min); + const pixY = Math.floor(128*(evt.clientY-(height-min)/2)/min); + if (pixX < 0 || pixX > 128 || pixY < 0 || pixY > 128) { + return null; + } return { x: pixX, y: pixY, } } +const pushEvent = (type: MouseEventType, evt: WindowMouseEvent, extra?: Partial) => { + const coords = eventPixelCoords(evt); + if (!coords) { + return + } + mouseEvents.push({type, button: evt.button, ...coords, ...(extra ?? {})}); +} + +const evtInBounds = (evt: WindowMouseEvent) => { + return !!eventPixelCoords(evt); +} + addEventListener("dblclick", (evt) => { - mouseEvents.push({type: "dblclick", button: evt.button, ...eventPixelCoords(evt)}); + pushEvent("dblclick", evt); }); addEventListener("click", (evt) => { - mouseEvents.push({type: "click", button: evt.button, ...eventPixelCoords(evt)}); + pushEvent("click", evt); }); addEventListener("mousedown", (evt) => { - mouseButtonsDown[evt.button] = true; - mouseEvents.push({type: "down", button: evt.button, ...eventPixelCoords(evt)}); + if (evtInBounds(evt)) { + mouseButtonsDown[evt.button] = true; + } + pushEvent("down", evt); }); addEventListener("mouseup", (evt) => { - mouseButtonsDown[evt.button] = false; - mouseEvents.push({type: "up", button: evt.button, ...eventPixelCoords(evt)}); + if (evtInBounds(evt)) { + mouseButtonsDown[evt.button] = false; + } + pushEvent("up", evt); }); addEventListener("mousemove", (evt) => { const coords = eventPixelCoords(evt); - mouseEvents.push({type: "move", button: evt.button, ...eventPixelCoords(evt), prevX: mouseX, prevY: mouseY}); - mouseX = coords.x; - mouseY = coords.y; + pushEvent("up", evt, {prevX: mouseX, prevY: mouseY}); + if (coords) { + mouseX = coords.x; + mouseY = coords.y; + } }); export const mousePos = () => {