forked from neoelonmask1/flappykitty.online
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.js
More file actions
63 lines (54 loc) · 1.52 KB
/
Copy pathinput.js
File metadata and controls
63 lines (54 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// input.js — Unified input handler
import { CONFIG } from './config.js';
let lastInputTime = 0;
let actionCallback = null;
let tapX = 0, tapY = 0;
let hasTap = false;
let scale = 1;
let canvasRect = null;
export function initInput(canvas, callback) {
actionCallback = callback;
function updateRect() {
canvasRect = canvas.getBoundingClientRect();
scale = CONFIG.CANVAS_W / canvasRect.width;
}
updateRect();
window.addEventListener('resize', updateRect);
function getLogicalPos(clientX, clientY) {
return {
x: (clientX - canvasRect.left) * scale,
y: (clientY - canvasRect.top) * scale,
};
}
function handleAction(clientX, clientY) {
const now = Date.now();
if (now - lastInputTime < CONFIG.INPUT_DEBOUNCE_MS) return;
lastInputTime = now;
const pos = getLogicalPos(clientX, clientY);
tapX = pos.x;
tapY = pos.y;
hasTap = true;
if (actionCallback) actionCallback(pos.x, pos.y);
}
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
const touch = e.touches[0];
handleAction(touch.clientX, touch.clientY);
}, { passive: false });
canvas.addEventListener('click', (e) => {
handleAction(e.clientX, e.clientY);
});
document.addEventListener('keydown', (e) => {
if (e.code === 'Space' || e.code === 'ArrowUp') {
e.preventDefault();
handleAction(CONFIG.CANVAS_W / 2, CONFIG.CANVAS_H / 2);
}
});
}
export function getTap() {
if (hasTap) {
hasTap = false;
return { x: tapX, y: tapY };
}
return null;
}