barkour/js/input.js

32 lines
1.2 KiB
JavaScript
Raw Normal View History

// Keyboard → input bitmasks. Two local slots; netplay merges both slots so the
// online player can use either WASD or arrows.
import { B } from './consts.js';
const MAPS = [
{ KeyA: B.L, KeyD: B.R, KeyW: B.U | B.JUMP, KeyS: B.D, KeyF: B.ATK, KeyG: B.SPC, KeyH: B.ITM },
{ ArrowLeft: B.L, ArrowRight: B.R, ArrowUp: B.U | B.JUMP, ArrowDown: B.D, KeyK: B.ATK, KeyL: B.SPC, Semicolon: B.ITM },
];
const bits = [0, 0];
const down = new Set();
const PREVENT = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Space']);
export function initInput() {
window.addEventListener('keydown', (e) => {
if (e.target && e.target.tagName === 'INPUT') return; // leave text fields alone
if (PREVENT.has(e.code)) e.preventDefault();
if (down.has(e.code)) return;
down.add(e.code);
for (let s = 0; s < 2; s++) if (MAPS[s][e.code]) bits[s] |= MAPS[s][e.code];
});
window.addEventListener('keyup', (e) => {
down.delete(e.code);
for (let s = 0; s < 2; s++) if (MAPS[s][e.code]) bits[s] &= ~MAPS[s][e.code];
});
window.addEventListener('blur', () => { bits[0] = 0; bits[1] = 0; down.clear(); });
}
export function getBits(slot) { return bits[slot]; }
export function getMergedBits() { return bits[0] | bits[1]; }