Mouse!
This commit is contained in:
88
mouse.ts
Normal file
88
mouse.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { WindowMouseEvent } from "https://deno.land/x/dwm@0.3.3/mod.ts";
|
||||
import { gameWindow } from "./window.ts";
|
||||
|
||||
export const M = {
|
||||
NONE: -1,
|
||||
LEFT: 0,
|
||||
RIGHT: 1,
|
||||
MIDDLE: 2,
|
||||
}
|
||||
|
||||
const mouseButtonsDown = {
|
||||
[M.LEFT]: false,
|
||||
[M.RIGHT]: false,
|
||||
[M.MIDDLE]: false,
|
||||
};
|
||||
const mouseEvents: Array<{
|
||||
type: "click" | "down" | "up" | "move",
|
||||
button: typeof M[keyof typeof M],
|
||||
x: number,
|
||||
y: number,
|
||||
prevX?: number,
|
||||
prevY?: number
|
||||
}> = [];
|
||||
|
||||
let mouseX = 0;
|
||||
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);
|
||||
return {
|
||||
x: pixX,
|
||||
y: pixY,
|
||||
}
|
||||
}
|
||||
|
||||
// addEventListener("dblclick", (evt) => {
|
||||
// console.log("dblclick", evt.button, evt.clientX, evt.clientY);
|
||||
// });
|
||||
|
||||
addEventListener("click", (evt) => {
|
||||
mouseEvents.push({type: "click", button: evt.button, ...eventPixelCoords(evt)});
|
||||
});
|
||||
|
||||
addEventListener("mousedown", (evt) => {
|
||||
mouseButtonsDown[evt.button] = true;
|
||||
mouseEvents.push({type: "down", button: evt.button, ...eventPixelCoords(evt)});
|
||||
});
|
||||
|
||||
addEventListener("mouseup", (evt) => {
|
||||
mouseButtonsDown[evt.button] = false;
|
||||
mouseEvents.push({type: "up", button: evt.button, ...eventPixelCoords(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;
|
||||
});
|
||||
|
||||
export const mousePos = () => {
|
||||
return {
|
||||
x: mouseX,
|
||||
y: mouseY,
|
||||
}
|
||||
}
|
||||
|
||||
export const getMouseX = () => {
|
||||
return mouseX;
|
||||
}
|
||||
|
||||
export const getMouseY = () => {
|
||||
return mouseY;
|
||||
}
|
||||
|
||||
export const refreshMouse = () => {
|
||||
mouseEvents.length = 0;
|
||||
}
|
||||
|
||||
export const mouseClick = (button: number = M.LEFT) => {
|
||||
return mouseEvents.some(ev => ev.button === button && ev.type === "click");
|
||||
}
|
||||
|
||||
export const mouseHeld = (button: number = M.LEFT) => {
|
||||
return mouseButtonsDown[button];
|
||||
}
|
Reference in New Issue
Block a user