Skip to content

Instantly share code, notes, and snippets.

@jdjkelly
Created March 3, 2013 18:47
Show Gist options
  • Save jdjkelly/5077582 to your computer and use it in GitHub Desktop.
Save jdjkelly/5077582 to your computer and use it in GitHub Desktop.
controller =
###
From HTML5Rocks
Even if you connect the gamepad, it won't manifest itself in any way unless the user
presses any of its buttons first. This is to prevent fingerprinting, although proves to be
a bit of a challenge for user experience: you can't ask the user to press the button or
provide gamepad-specific instructions because you have no idea whether they connected
their controller.
Chrome's implementation of the API exposes a function – navigator.webkitGetGamepads() –
you can use to get a list of all the gamepads currently plugged into to the system,
alongside with their current state (buttons + sticks). The first connected gamepad will
be returned as the first entry in the array, and so on.
The so-far-implemented part of the spec requires you to continuously check the state of
connected gamepads (and compare it to the previous one if necessary), instead of firing
events when things change.
###
gamepad: null
prevTimestamp: null
prevRawGamepadType: null
ticking: false
init: ->
# Gamepad Detection
gamepadSupportAvailable = !!navigator.webkitGetGamepads
if gamepadSupportAvailable
controller.startPolling()
startPolling: ->
if not controller.ticking
controller.ticking = true
controller.tick()
tick: ->
controller.pollStatus()
controller.scheduleNextTick()
pollStatus: ->
controller.pollGamepads()
if controller.gamePad?
controller.prevTimestamp = gamepad.timestamp
controller.updateDisplay()
pollGamepads: ->
rawGamepads = navigator.webkitGetGamepads()
if rawGamepads
gamepadsChanged = false
console.log typeof rawGamepads[0]
if typeof rawGamepads[0] != controller.preRawGamepadType
gamepadsChanged = true
controller.prevRawGamepadType = typeof rawGamepads[0]
if gamepadsChanged
console.log controller.prevRawGamepadType
updateDisplay: ->
$('h1').text 'updatedDisplay' + Date.now()
scheduleNextTick: ->
if controller.ticking
window.requestAnimationFrame ->
controller.tick()
controller.init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment