summaryrefslogtreecommitdiffstats
path: root/src/view/input/gameinput.ts
diff options
context:
space:
mode:
authorMatthias Schiffer <mschiffer@universe-factory.net>2018-11-09 13:27:49 +0100
committerMatthias Schiffer <mschiffer@universe-factory.net>2018-11-09 13:27:49 +0100
commit453a9391ccf1ab0c7a6869c44664bfcdd1b68fa1 (patch)
tree1990de3e2da6c88cf48310a53937d0decac20329 /src/view/input/gameinput.ts
parente0eddb8741b840df97380e557abd51b47a5e2eee (diff)
downloadrpgedit-453a9391ccf1ab0c7a6869c44664bfcdd1b68fa1.tar
rpgedit-453a9391ccf1ab0c7a6869c44664bfcdd1b68fa1.zip
Allow interacting with entities
Diffstat (limited to 'src/view/input/gameinput.ts')
-rw-r--r--src/view/input/gameinput.ts78
1 files changed, 78 insertions, 0 deletions
diff --git a/src/view/input/gameinput.ts b/src/view/input/gameinput.ts
new file mode 100644
index 0000000..f3066e3
--- /dev/null
+++ b/src/view/input/gameinput.ts
@@ -0,0 +1,78 @@
+import { InputHandler } from './inputhandler';
+
+import { Listenable } from '../../util';
+
+import { vec2 } from 'gl-matrix';
+
+export enum ButtonCode {
+ Action,
+ Back,
+ Menu,
+}
+
+const buttonMapping: {[key: string]: ButtonCode} = {
+ KeyZ: ButtonCode.Action,
+ KeyX: ButtonCode.Back,
+ KeyC: ButtonCode.Menu,
+};
+
+export interface DirectionInput {
+ type: 'direction';
+ direction: vec2;
+}
+
+export interface ButtonInput {
+ type: 'button';
+ button: ButtonCode;
+}
+
+export type GameInput = DirectionInput | ButtonInput;
+
+export class GameInputHandler extends Listenable<[GameInput]> {
+ private readonly input: InputHandler;
+
+ constructor() {
+ super();
+
+ this.input = new InputHandler(
+ new Set([
+ 'ArrowLeft',
+ 'ArrowUp',
+ 'ArrowRight',
+ 'ArrowDown',
+ ...Object.keys(buttonMapping),
+ ]));
+
+ this.input.addListener((key: string, pressed: boolean) => {
+ const button = buttonMapping[key];
+ if (button !== undefined) {
+ if (pressed)
+ this.runListeners({
+ type: 'button',
+ button,
+ });
+
+ return;
+ }
+
+ const dir = vec2.create();
+
+ if (this.input.has('ArrowLeft'))
+ vec2.add(dir, dir, [-1, 0]);
+ if (this.input.has('ArrowUp'))
+ vec2.add(dir, dir, [0, -1]);
+ if (this.input.has('ArrowRight'))
+ vec2.add(dir, dir, [1, 0]);
+ if (this.input.has('ArrowDown'))
+ vec2.add(dir, dir, [0, 1]);
+
+ if (vec2.sqrLen(dir) > 0)
+ vec2.normalize(dir, dir);
+
+ this.runListeners({
+ type: 'direction',
+ direction: dir,
+ });
+ });
+ }
+}