assassin-bug/framework/input/inputs/mouse.js

88 lines
3.2 KiB
JavaScript
Raw Permalink Normal View History

2022-11-26 01:22:02 +00:00
import { BaseInput } from './base-input';
export class Mouse extends BaseInput {
constructor(element) {
super(element);
this.mousePosition = new Position();
this.mouseDelta = new Delta();
this.mouseWheel = new Delta();
this.mouseButtons = new MouseButtons();
}
capture() {
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handlePointerChange = this.handlePointerChange.bind(this);
this.active = true;
this.element.addEventListener('mousedown', this.handleMouseDown);
this.element.addEventListener('mousemove', this.handleMouseMove);
this.element.addEventListener('mouseup', this.handleMouseUp);
document.addEventListener('pointerlockchange', this.handlePointerChange);
}
release() {
this.active = false;
this.element.removeEventListener('mousedown', this.handleMouseDown);
this.element.removeEventListener('mousemove', this.handleMouseMove);
this.element.removeEventListener('mouseup', this.handleMouseUp);
}
getState() {
const { mouseButtons, mouseDelta, mousePosition, mouseWheel } = this;
const state = {
mouseButtons: {
keysDown: new Map(this.mouseButtons.keysDown),
keysJustPressed: new Map(this.mouseButtons.keysJustPressed),
keysJustReleased: new Map(this.mouseButtons.keysJustReleased)
},
mouseDelta,
mousePosition,
mouseWheel
};
this.mouseButtons.keysJustPressed.clear();
this.mouseButtons.keysJustReleased.clear();
this.mouseDelta.x = 0;
this.mouseDelta.y = 0;
return state;
}
handleMouseDown(event) {
if (this.active)
event.preventDefault();
this.mouseButtons.keysDown.set(event.button, true);
this.mouseButtons.keysJustPressed.set(event.button, true);
this.mouseButtons.keysJustReleased.set(event.button, false);
}
handleMouseMove(event) {
if (this.active)
event.preventDefault();
this.mousePosition.x = event.clientX;
this.mousePosition.y = event.clientY;
this.mouseDelta.x = event.movementX;
this.mouseDelta.y = event.movementY;
}
handleMouseUp(event) {
if (this.active)
event.preventDefault();
this.mouseButtons.keysJustReleased.set(event.button, true);
this.mouseButtons.keysDown.set(event.button, false);
this.mouseButtons.keysJustPressed.set(event.button, false);
}
handlePointerChange() {
if (document.pointerLockElement !== this.element) {
this.element.addEventListener('click', () => {
this.element.requestPointerLock();
}, {
once: true
});
}
}
}
export class Position {
}
export class MouseButtons {
constructor() {
this.keysDown = new Map();
this.keysJustPressed = new Map();
this.keysJustReleased = new Map();
}
}
export class Delta {
}