83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
'use strict';
|
|
|
|
// === KEYBOARD INPUT SYSTEM ===
|
|
|
|
const inputSystem = {
|
|
keys: {},
|
|
justPressed: {},
|
|
actions: {},
|
|
|
|
init() {
|
|
document.addEventListener('keydown', (e) => {
|
|
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space', 'Enter', 'ShiftLeft', 'ShiftRight', 'KeyE', 'KeyI', 'KeyQ', 'Tab'].includes(e.code)) {
|
|
e.preventDefault();
|
|
}
|
|
if (!this.keys[e.code]) {
|
|
this.justPressed[e.code] = true;
|
|
}
|
|
this.keys[e.code] = true;
|
|
});
|
|
document.addEventListener('keyup', (e) => {
|
|
this.keys[e.code] = false;
|
|
});
|
|
},
|
|
|
|
clearKeys() {
|
|
this.keys = {};
|
|
this.justPressed = {};
|
|
},
|
|
|
|
update(dt) {
|
|
// Process actions
|
|
this.actions = {
|
|
move: this.getMove(),
|
|
attack: this.justPressed['Space'] || this.justPressed['KeyZ'],
|
|
interact: this.justPressed['KeyE'] || this.justPressed['Enter'],
|
|
menu: this.justPressed['KeyI'],
|
|
back: this.justPressed['Escape'] || this.justPressed['KeyQ'],
|
|
switchWeapon: this.justPressed['KeyX'],
|
|
useItem: this.justPressed['KeyR'],
|
|
bomb: this.justPressed['KeyB'],
|
|
};
|
|
|
|
// Clear justPressed for next frame
|
|
this.justPressed = {};
|
|
},
|
|
|
|
getMove() {
|
|
let dx = 0, dy = 0;
|
|
if (this.keys['ArrowUp'] || this.keys['KeyW']) dy = -1;
|
|
else if (this.keys['ArrowDown'] || this.keys['KeyS']) dy = 1;
|
|
if (this.keys['ArrowLeft'] || this.keys['KeyA']) dx = -1;
|
|
else if (this.keys['ArrowRight'] || this.keys['KeyD']) dx = 1;
|
|
if (dx !== 0 || dy !== 0) return { dx, dy };
|
|
return null;
|
|
},
|
|
|
|
getAction(name) {
|
|
return this.actions[name] || false;
|
|
},
|
|
|
|
isKeyDown(code) {
|
|
return !!this.keys[code];
|
|
},
|
|
|
|
wasKeyPressed(code) {
|
|
return !!this.justPressed[code];
|
|
},
|
|
};
|
|
|
|
function initKeyboard() {
|
|
inputSystem.init();
|
|
}
|
|
|
|
if (typeof module !== 'undefined' && module.exports) {
|
|
module.exports = { inputSystem, initKeyboard, isKeyDown: (code) => inputSystem.isKeyDown(code),
|
|
isKeyJustPressed: (code) => inputSystem.wasKeyPressed(code),
|
|
setKeyHandlers: () => {},
|
|
resetKeys: () => inputSystem.clearKeys(),
|
|
getMove: () => inputSystem.getMove(),
|
|
getAction: (name) => inputSystem.getAction(name),
|
|
clearKeys: () => inputSystem.clearKeys(),
|
|
update: (dt) => inputSystem.update(dt) };
|
|
} |