Skip to content

Instantly share code, notes, and snippets.

@robpataki
Last active October 13, 2023 15:23
Show Gist options
  • Save robpataki/bd736b5c19633f0caad9181e9eb2b0cf to your computer and use it in GitHub Desktop.
Save robpataki/bd736b5c19633f0caad9181e9eb2b0cf to your computer and use it in GitHub Desktop.
Pointer utility class for tracking pointer movement and clicks
let instance: Pointer;
/**
* Tracks the pointer in WebGL
*/
export default class Pointer {
/**
* Current coordinates
* @return {x: number, y: number} The current pointer coordinates.
*/
public pointer = { x: 0, y: 0 };
/**
* Current pressed state
* @return boolean `true` when the pointer is pressed.
*/
public isPressed = false;
constructor() {
if (!window) {
return;
}
if (!instance) {
instance = this;
this.init();
}
return instance;
}
private init() {
window.addEventListener('pointermove', this.handlePointerMove.bind(this));
window.addEventListener('pointerdown', this.handlePointerDown.bind(this));
window.addEventListener('pointerup', this.handlePointerUp.bind(this));
}
private handlePointerMove(event: PointerEvent) {
this.pointer.x = (event.clientX / window.outerWidth) * 2 - 1;
this.pointer.y = -(event.clientY / window.outerHeight) * 2 + 1;
}
private handlePointerDown() {
this.isPressed = true;
}
private handlePointerUp() {
this.isPressed = false;
}
/**
* Clean up and remove event listeners
*/
dispose() {
window.removeEventListener('pointermove', this.handlePointerMove);
window.removeEventListener('pointermove', this.handlePointerDown);
window.removeEventListener('pointermove', this.handlePointerUp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment