add key events
This commit is contained in:
parent
2104e752ad
commit
b9dbcc5de8
@ -1,4 +1,8 @@
|
||||
export class Gamelib {
|
||||
keysPressed = new Set();
|
||||
keyPressHandlers = new Map();
|
||||
keyReleaseHandlers = new Map();
|
||||
|
||||
constructor(console, codeStopper, spriteProvider, canvasElement) {
|
||||
this.console = console;
|
||||
this.codeStopper = codeStopper;
|
||||
@ -11,6 +15,16 @@ export class Gamelib {
|
||||
this.canvas.height = this.height;
|
||||
this.cx = this.canvas.getContext("2d");
|
||||
this.cx.imageSmootingEnabled = false;
|
||||
|
||||
document.body.addEventListener("keydown", (ev) => {
|
||||
this.keysPressed.add(ev.key);
|
||||
this.keyPressHandlers.get(ev.key)?.();
|
||||
});
|
||||
|
||||
document.body.addEventListener("keyup", (ev) => {
|
||||
this.keysPressed.delete(ev.key);
|
||||
this.keyReleaseHandlers.get(ev.key)?.();
|
||||
});
|
||||
}
|
||||
|
||||
println(msg) {
|
||||
@ -35,6 +49,18 @@ export class Gamelib {
|
||||
});
|
||||
}
|
||||
|
||||
isPressed(key) {
|
||||
return this.keysPressed.has(key);
|
||||
}
|
||||
|
||||
onPress(key, handlerFunction) {
|
||||
this.keyPressHandlers.set(key, handlerFunction);
|
||||
}
|
||||
|
||||
onRelease(key, handlerFunction) {
|
||||
this.keyReleaseHandlers.set(key, handlerFunction);
|
||||
}
|
||||
|
||||
rgb(red, green, blue) {
|
||||
return `rgb(${red}, ${green}, ${blue})`;
|
||||
}
|
||||
|
@ -58,6 +58,7 @@ runButton.onclick = (ev) => {
|
||||
karlkoder.lib().spriteProvider.injectSprites(spriteEditor.sprites);
|
||||
codeRunner.setCode(code);
|
||||
codeRunner.toggle();
|
||||
document.querySelector("canvas").focus();
|
||||
|
||||
if (codeRunner.isRunning) {
|
||||
runButton.textContent = "✋ Stop";
|
||||
|
Loading…
x
Reference in New Issue
Block a user