import { Vec2 } from "./vector"; export class MouseController { private readonly debounce_ms = 400; private readonly movement_threshold = 40; private last_event_time = Date.now(); private movement_queue: Vec2[] = []; private interval_id: number | null = null; constructor(private readonly callback: (new_movement: Vec2) => void) {} public start() { if (this.interval_id !== null) { return; } this.interval_id = setInterval(() => { this.publish_movement(); }, this.debounce_ms); } public stop() { if (this.interval_id === null) { return; } clearInterval(this.interval_id); this.interval_id = null; } public move(x: number, y: number) { const new_movement = new Vec2(x, y); const last_movement = this.movement_queue.at(-1); this.movement_queue.push(new_movement); if ( typeof last_movement === "undefined" || new_movement.distance_to(last_movement) < this.movement_threshold ) { return; } this.publish_movement(); } private publish_movement() { if ( Date.now() - this.last_event_time < this.debounce_ms || this.movement_queue.length === 0 ) { return; } this.last_event_time = Date.now(); this.callback(this.movement_queue.at(-1)!); this.movement_queue = []; } }