mirror of
https://gitlab.com/Oreolek/salet-gamepad-module.git
synced 2024-04-26 22:29:39 +03:00
56 lines
1.8 KiB
CoffeeScript
56 lines
1.8 KiB
CoffeeScript
# Gamepad HTML5 API
|
|
class Gamepad
|
|
constructor: (pad) ->
|
|
@gamepad = pad
|
|
@map = @detectMapping(pad.id, navigator.userAgent)
|
|
@pressed = @getPressed()
|
|
detectMapping: (id, browser) ->
|
|
for map in salet.view.gamepadmappings
|
|
for device in map.supported
|
|
if id.indexOf(device.id) != -1 and browser.indexOf(device.browser) != -1
|
|
return map
|
|
# mapping not found, return the first map for this browser
|
|
for device in map.supported
|
|
if browser.indexOf(device.browser) != -1
|
|
return map
|
|
# browser and device are not supported, just return the first map
|
|
console.warn "Browser and device are not found, gamepad support not guaranteed."
|
|
return salet.view.gamepadmappings[0]
|
|
axis: (name) ->
|
|
map = @map.axes[name]
|
|
unless map?
|
|
return 0
|
|
if map.index?
|
|
return @gamepad.axes[map.index]
|
|
if map.buttonPositive? and @gamepad.buttons[map.buttonPositive].pressed
|
|
return 1
|
|
if map.buttonNegative? and @gamepad.buttons[map.buttonNegative].pressed
|
|
return -1
|
|
return 0
|
|
button: (name) ->
|
|
map = @map.buttons[name]
|
|
unless map?
|
|
return 0
|
|
if map.index? and @gamepad.buttons[map.index]?
|
|
return @gamepad.buttons[map.index].pressed
|
|
if map.axis?
|
|
if map.direction < 0
|
|
return @gamepad.axes[map.axis] < -0.75
|
|
else
|
|
return @gamepad.axes[map.axis] > 0.75
|
|
return false
|
|
# Return the name of the pressed button
|
|
getPressed: () ->
|
|
for buttonname, button of @map.buttons
|
|
if (
|
|
@gamepad.buttons[button.index]? and
|
|
@gamepad.buttons[button.index].pressed
|
|
) or (
|
|
@gamepad.axes[button.axis] < -0.75 and
|
|
button.direction < 0
|
|
) or (
|
|
@gamepad.axes[button.axis] > 0.75 and
|
|
button.direction > 0
|
|
)
|
|
return buttonname
|