nordic-skating / local-littlejs / files / src / input.ts
Branch local-littlejs · default branch · all branches
input.ts
| 1 | /** How far a finger has to be dragged sideways for full steering, CSS pixels. */ |
| 2 | const FULL_DRAG = 70 |
| 3 | |
| 4 | /** |
| 5 | * Tilting the phone to steer: how far over, in degrees, counts as nothing, since nobody |
| 6 | * holds a phone dead level, and how far is full steering. |
| 7 | */ |
| 8 | const TILT_REST = 4 |
| 9 | const TILT_FULL = 28 |
| 10 | |
| 11 | /** |
| 12 | * Steering from how a phone is held: -1 (hard left) to 1 (hard right), 0 when it is |
| 13 | * level from side to side. The phone is turned like a wheel, about the line the skater |
| 14 | * looks along. |
| 15 | * |
| 16 | * `beta` and `gamma` are what the phone reports, in degrees: how far it is tipped top |
| 17 | * edge up, and how far it is rolled right edge down, both as if it were held upright. |
| 18 | * `turned` is how the screen is turned from upright, in degrees, as `screen.orientation` |
| 19 | * has it: held on its side, the roll that steers is what the phone calls its tip. |
| 20 | */ |
| 21 | export function tiltSteer(beta: number, gamma: number, turned: number): number { |
| 22 | const roll = turned === 90 ? beta : turned === 270 ? -beta : turned === 180 ? -gamma : gamma |
| 23 | const past = Math.abs(roll) - TILT_REST |
| 24 | return past <= 0 ? 0 : Math.sign(roll) * Math.min(1, past / (TILT_FULL - TILT_REST)) |
| 25 | } |
| 26 | |
| 27 | /** How far a controller's stick is from its middle before it counts: a stick at rest is never quite at it. */ |
| 28 | const PAD_REST = 0.15 |
| 29 | |
| 30 | /** Steering from a controller's stick, pushed `lean` of the way over, -1 to 1: nothing near its middle, and easing in from there. */ |
| 31 | export function padSteer(lean: number): number { |
| 32 | const past = Math.abs(lean) - PAD_REST |
| 33 | return past <= 0 ? 0 : Math.sign(lean) * Math.min(1, past / (1 - PAD_REST)) |
| 34 | } |
| 35 | |
| 36 | /** What iPhones add to the event: steering by tilt has to be asked for, and at a touch. */ |
| 37 | type Asking = typeof DeviceOrientationEvent & { requestPermission?: () => Promise<'granted' | 'denied'> } |
| 38 | |
| 39 | /** |
| 40 | * Steering, from whatever is to hand: a finger or mouse dragged sideways from where it |
| 41 | * went down, the arrow keys or A and D, a game controller's stick or direction buttons, |
| 42 | * or, if it has been turned on, the tilt of a phone. |
| 43 | */ |
| 44 | export class Input { |
| 45 | private pointer: number | null = null |
| 46 | private startX = 0 |
| 47 | private drag = 0 |
| 48 | private tilt = 0 |
| 49 | private pad = 0 |
| 50 | /** The controller buttons that were down the last time they were read. */ |
| 51 | private padDown = new Set<number>() |
| 52 | private readonly keys = new Set<string>() |
| 53 | private readonly tilted = (e: DeviceOrientationEvent): void => { |
| 54 | if (e.beta === null || e.gamma === null) return |
| 55 | // Eased a little: a hand is never still, and the reports come many times a second. |
| 56 | this.tilt += 0.3 * (tiltSteer(e.beta, e.gamma, screen.orientation?.angle ?? 0) - this.tilt) |
| 57 | } |
| 58 | |
| 59 | /** Whether this is a device that can be steered by tilting it: a phone or a tablet. */ |
| 60 | static get canTilt(): boolean { |
| 61 | return 'DeviceOrientationEvent' in window && matchMedia('(pointer: coarse)').matches |
| 62 | } |
| 63 | |
| 64 | /** Whether turning tilt on has to wait for a touch, as it does on an iPhone. */ |
| 65 | static get tiltNeedsTouch(): boolean { |
| 66 | return typeof (window.DeviceOrientationEvent as Asking | undefined)?.requestPermission === 'function' |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Start steering by tilt. On an iPhone this asks the skater's leave, which the browser |
| 71 | * allows only from within a touch. Answers whether it was given. |
| 72 | */ |
| 73 | async tiltOn(): Promise<boolean> { |
| 74 | try { |
| 75 | const ask = (window.DeviceOrientationEvent as Asking | undefined)?.requestPermission |
| 76 | if (ask && (await ask()) !== 'granted') return false |
| 77 | } catch { |
| 78 | return false |
| 79 | } |
| 80 | window.addEventListener('deviceorientation', this.tilted) |
| 81 | return true |
| 82 | } |
| 83 | |
| 84 | tiltOff(): void { |
| 85 | window.removeEventListener('deviceorientation', this.tilted) |
| 86 | this.tilt = 0 |
| 87 | } |
| 88 | |
| 89 | constructor(target: HTMLElement) { |
| 90 | target.addEventListener('pointerdown', (e) => { |
| 91 | if (this.pointer !== null) return |
| 92 | this.pointer = e.pointerId |
| 93 | this.startX = e.clientX |
| 94 | this.drag = 0 |
| 95 | target.setPointerCapture(e.pointerId) |
| 96 | }) |
| 97 | target.addEventListener('pointermove', (e) => { |
| 98 | if (e.pointerId === this.pointer) this.drag = (e.clientX - this.startX) / FULL_DRAG |
| 99 | }) |
| 100 | const release = (e: PointerEvent): void => { |
| 101 | if (e.pointerId !== this.pointer) return |
| 102 | this.pointer = null |
| 103 | this.drag = 0 |
| 104 | } |
| 105 | target.addEventListener('pointerup', release) |
| 106 | target.addEventListener('pointercancel', release) |
| 107 | window.addEventListener('keydown', (e) => this.keys.add(e.code)) |
| 108 | window.addEventListener('keyup', (e) => this.keys.delete(e.code)) |
| 109 | // A key held while the window loses focus never sends its keyup. |
| 110 | window.addEventListener('blur', () => this.keys.clear()) |
| 111 | } |
| 112 | |
| 113 | /** -1 (hard left) to 1 (hard right); 0 when nothing is being pressed. */ |
| 114 | steer(): number { |
| 115 | const held = (...codes: string[]): number => (codes.some((c) => this.keys.has(c)) ? 1 : 0) |
| 116 | const keys = held('ArrowRight', 'KeyD') - held('ArrowLeft', 'KeyA') |
| 117 | return Math.max(-1, Math.min(1, keys + this.drag + this.tilt + this.pad)) |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Read the game controllers, which have to be asked: they send nothing of their own |
| 122 | * accord. Called once a frame. Answers which of their buttons have just been pressed, |
| 123 | * by the numbers of the standard layout: 2 is X or square, 3 is Y or triangle. |
| 124 | */ |
| 125 | pollPads(): number[] { |
| 126 | const pressed: number[] = [] |
| 127 | const down = new Set<number>() |
| 128 | this.pad = 0 |
| 129 | for (const pad of navigator.getGamepads?.() ?? []) { |
| 130 | if (!pad) continue |
| 131 | // Either stick, or the direction buttons, whichever is pushed furthest. |
| 132 | const left = pad.buttons[14]?.pressed ? -1 : 0 |
| 133 | const right = pad.buttons[15]?.pressed ? 1 : 0 |
| 134 | for (const lean of [pad.axes[0] ?? 0, pad.axes[2] ?? 0, left + right]) { |
| 135 | const steer = padSteer(lean) |
| 136 | if (Math.abs(steer) > Math.abs(this.pad)) this.pad = steer |
| 137 | } |
| 138 | pad.buttons.forEach((button, n) => { |
| 139 | if (!button.pressed) return |
| 140 | down.add(n) |
| 141 | if (!this.padDown.has(n)) pressed.push(n) |
| 142 | }) |
| 143 | } |
| 144 | this.padDown = down |
| 145 | return pressed |
| 146 | } |
| 147 | } |