Skip to content

Commit

Permalink
feat(Gamepad class): implement stick() method
Browse files Browse the repository at this point in the history
  • Loading branch information
niklashigi committed Jan 3, 2018
1 parent 449215b commit ec1d56d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/inputs/gamepad.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ describe('The `Gamepad` class', () => {
pressed: false,
},
],
axes: [],
axes: [0, 0, 0, 0],
connected: true,
timestamp: 0,
}
Expand Down Expand Up @@ -163,6 +163,30 @@ describe('The `Gamepad` class', () => {

})

describe('should have a `stick()` method that returns a component that', () => {

it('throws an error when initialized with an invalid stick', () => {
expect(() => gamepad.stick('lol')).to.throw(Error, 'Gamepad stick "lol" not found!')
})

it('returns a (0, 0) vector when initially queried', () => {
expect(gamepad.stick('left')).to.deep.equal(new Vector2())
})

it('returns the correct vector when queried after change', () => {
nav.gamepads[0].axes[0] = .56
nav.gamepads[0].axes[1] = .31
expect(gamepad.stick('left')).to.deep.equal(new Vector2(.56, .31))
})

it('also works with custom axis numbers', () => {
nav.gamepads[0].axes[2] = .42
nav.gamepads[0].axes[3] = .69
expect(gamepad.stick({ xAxis: 2, yAxis: 3 })).to.deep.equal(new Vector2(.42, .69))
})

})

})

})
24 changes: 24 additions & 0 deletions src/inputs/gamepad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ import { IGamepad, INavigator, IWindow } from '../apis'
import { Control } from '../core/control'
import { store } from '../index'
import { findButtonNumber, getButtonLabel } from '../maps/gamepad'
import { Vector2 } from '../utils/math'

export interface GamepadStick {

xAxis: number
yAxis: number

}

const gamepadSticks: { [id: string]: GamepadStick } = {
left: { xAxis: 0, yAxis: 1 },
right: { xAxis: 2, yAxis: 3 },
}

export class Gamepad {

Expand Down Expand Up @@ -71,4 +84,15 @@ export class Gamepad {
}
}

public stick(stick: string | GamepadStick): Vector2 {
if (typeof stick === 'string') {
if (stick in gamepadSticks) {
stick = gamepadSticks[stick]
} else {
throw new Error(`Gamepad stick "${stick}" not found!`)
}
}
return new Vector2(this.gamepad.axes[stick.xAxis], this.gamepad.axes[stick.yAxis])
}

}

0 comments on commit ec1d56d

Please sign in to comment.