Skip to content

Commit

Permalink
fix: make Gamepad.stick consistent with the docs
Browse files Browse the repository at this point in the history
  • Loading branch information
niklashigi committed Sep 29, 2018
1 parent fd07ebc commit 58b26e6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
6 changes: 3 additions & 3 deletions src/inputs/gamepad.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,19 +170,19 @@ describe('The `Gamepad` class', () => {
})

it('returns a (0, 0) vector when initially queried', () => {
expect(gamepad.stick('left')).to.deep.equal(new Vector2())
expect(gamepad.stick('left').query()).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))
expect(gamepad.stick('left').query()).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))
expect(gamepad.stick({ label: '', xAxis: 2, yAxis: 3 }).query()).to.deep.equal(new Vector2(.42, .69))
})

})
Expand Down
21 changes: 16 additions & 5 deletions src/inputs/gamepad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import { Vector2 } from '../utils/math'

export interface GamepadStick {

label: string
xAxis: number
yAxis: number

}

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

export class Gamepad {
Expand Down Expand Up @@ -93,15 +94,25 @@ export class Gamepad {
}
}

public stick(stick: string | GamepadStick): Vector2 {
public stick(stick: string | GamepadStick): Control<Vector2> {
let gpStick: GamepadStick
if (typeof stick === 'string') {
if (stick in gamepadSticks) {
stick = gamepadSticks[stick]
gpStick = gamepadSticks[stick]
} else {
throw new Error(`Gamepad stick "${stick}" not found!`)
}
} else {
gpStick = stick
}

const {gamepad} = this
return {
label: gpStick.label,
query() {
return new Vector2(gamepad.axes[gpStick.xAxis], gamepad.axes[gpStick.yAxis])
},
}
return new Vector2(this.gamepad.axes[stick.xAxis], this.gamepad.axes[stick.yAxis])
}

}

0 comments on commit 58b26e6

Please sign in to comment.