Skip to content

Commit ec1d56d

Browse files
committed
feat(Gamepad class): implement stick() method
1 parent 449215b commit ec1d56d

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/inputs/gamepad.spec.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ describe('The `Gamepad` class', () => {
120120
pressed: false,
121121
},
122122
],
123-
axes: [],
123+
axes: [0, 0, 0, 0],
124124
connected: true,
125125
timestamp: 0,
126126
}
@@ -163,6 +163,30 @@ describe('The `Gamepad` class', () => {
163163

164164
})
165165

166+
describe('should have a `stick()` method that returns a component that', () => {
167+
168+
it('throws an error when initialized with an invalid stick', () => {
169+
expect(() => gamepad.stick('lol')).to.throw(Error, 'Gamepad stick "lol" not found!')
170+
})
171+
172+
it('returns a (0, 0) vector when initially queried', () => {
173+
expect(gamepad.stick('left')).to.deep.equal(new Vector2())
174+
})
175+
176+
it('returns the correct vector when queried after change', () => {
177+
nav.gamepads[0].axes[0] = .56
178+
nav.gamepads[0].axes[1] = .31
179+
expect(gamepad.stick('left')).to.deep.equal(new Vector2(.56, .31))
180+
})
181+
182+
it('also works with custom axis numbers', () => {
183+
nav.gamepads[0].axes[2] = .42
184+
nav.gamepads[0].axes[3] = .69
185+
expect(gamepad.stick({ xAxis: 2, yAxis: 3 })).to.deep.equal(new Vector2(.42, .69))
186+
})
187+
188+
})
189+
166190
})
167191

168192
})

src/inputs/gamepad.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@ import { IGamepad, INavigator, IWindow } from '../apis'
22
import { Control } from '../core/control'
33
import { store } from '../index'
44
import { findButtonNumber, getButtonLabel } from '../maps/gamepad'
5+
import { Vector2 } from '../utils/math'
6+
7+
export interface GamepadStick {
8+
9+
xAxis: number
10+
yAxis: number
11+
12+
}
13+
14+
const gamepadSticks: { [id: string]: GamepadStick } = {
15+
left: { xAxis: 0, yAxis: 1 },
16+
right: { xAxis: 2, yAxis: 3 },
17+
}
518

619
export class Gamepad {
720

@@ -71,4 +84,15 @@ export class Gamepad {
7184
}
7285
}
7386

87+
public stick(stick: string | GamepadStick): Vector2 {
88+
if (typeof stick === 'string') {
89+
if (stick in gamepadSticks) {
90+
stick = gamepadSticks[stick]
91+
} else {
92+
throw new Error(`Gamepad stick "${stick}" not found!`)
93+
}
94+
}
95+
return new Vector2(this.gamepad.axes[stick.xAxis], this.gamepad.axes[stick.yAxis])
96+
}
97+
7498
}

0 commit comments

Comments
 (0)