summaryrefslogtreecommitdiffstats
path: root/src/renderer/runtime/view/input/gameinput.ts
blob: b116839dcf3e49a7aaddaf749f33b4bd74baf35e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { InputHandler } from './inputhandler';

import { Listenable } from '../../util';

import { vec2 } from 'gl-matrix';

export enum ButtonCode {
	Action,
	Back,
	Menu,
}

const buttonMapping: Record<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,
			});
		});
	}
}