gale/keys.js
2025-02-14 07:58:29 -05:00

48 lines
1.1 KiB
JavaScript

const Move = {
Keys: ["w", "d", "s", "a"],
Pair: [ 2, 3, 0, 1 ],
Axis: [ 1, 0, 1, 0 ],
Magn: [-1, 1, 1, -1 ],
Down: [ 0, 0, 0, 0 ],
Move: [0, 0],
};
/** @type {Van.state<[x:number, y:number]>} */
export const Pos = van.state(Move.Move);
/** @type {(scale:number)=>string} */
export const PosCSS =(scale)=> `left:${Pos.val[0]*scale}px; top:${Pos.val[1]*scale}px;`;
function handleDown({key})
{
const index = Move.Keys.indexOf(key);
if(index != -1)
{
Move.Down[index] = 1;
Move.Move[Move.Axis[index]] = Move.Magn[index];
Pos.val = [...Move.Move];
}
}
function handleUp({key})
{
const index = Move.Keys.indexOf(key);
if(index != -1)
{
const indexInv = Move.Pair[index];
Move.Down[index] = 0;
if(Move.Down[indexInv])
{
Move.Move[Move.Axis[indexInv]] = Move.Magn[indexInv];
}
else
{
Move.Move[Move.Axis[index]] = 0;
}
Pos.val = [...Move.Move];
}
}
document.body.addEventListener("keydown", handleDown);
document.body.addEventListener("keyup", handleUp);