Add gamepad support
This commit is contained in:
parent
89474de3f3
commit
f074444521
|
@ -128,6 +128,7 @@ export function GameState(ctx: ContextI): StateI {
|
|||
}
|
||||
let elapsed: number = 0
|
||||
let update = (delta: number) => {
|
||||
checkGamepads()
|
||||
elapsed += delta
|
||||
modeTimer += delta
|
||||
if (isNight && modeTimer >= nightTime) {
|
||||
|
@ -222,15 +223,16 @@ export function GameState(ctx: ContextI): StateI {
|
|||
}
|
||||
|
||||
let desiredActions: Action[] = []
|
||||
let adjustAction = (type: string, v: number) => {
|
||||
let adjustAction = (type: string, v: number, inc?: boolean) => {
|
||||
let action = desiredActions.find(v=>v.type===type)
|
||||
if (!action) {
|
||||
if (v === 0) return
|
||||
desiredActions.push({
|
||||
type: type,
|
||||
priority: v,
|
||||
})
|
||||
} else {
|
||||
action.priority = v
|
||||
action.priority = inc?action.priority+v:v
|
||||
if (action.priority <= 0) {
|
||||
desiredActions = desiredActions.filter(v=>v!==action)
|
||||
}
|
||||
|
@ -268,9 +270,47 @@ export function GameState(ctx: ContextI): StateI {
|
|||
window.removeEventListener('keydown', keydown)
|
||||
}
|
||||
|
||||
let hookGamepad = () => {
|
||||
}
|
||||
let unhookGamepad = () => {
|
||||
let gamepads: Record<string, Gamepad> = {}
|
||||
window.addEventListener('gamepadconnected', (ev: GamepadEvent) => {
|
||||
gamepads[ev.gamepad.id] = ev.gamepad
|
||||
})
|
||||
window.removeEventListener('gamepaddisconnected', (ev: GamepadEvent) => {
|
||||
delete gamepads[ev.gamepad.id]
|
||||
})
|
||||
function checkGamepads() {
|
||||
//for (let gp of Object.values(gamepads)) {
|
||||
for (let gp of navigator.getGamepads()) {
|
||||
if (!gp || !gp.connected) break
|
||||
if (gp.axes[0] < 0) {
|
||||
adjustAction('west', Math.abs(gp.axes[0]))
|
||||
} else if (gp.axes[0] > 0) {
|
||||
adjustAction('east', gp.axes[0])
|
||||
} else {
|
||||
adjustAction('east', 0)
|
||||
adjustAction('west', 0)
|
||||
}
|
||||
if (gp.axes[1] < 0) {
|
||||
adjustAction('north', Math.abs(gp.axes[1]))
|
||||
} else if (gp.axes[1] > 0) {
|
||||
adjustAction('south', gp.axes[1])
|
||||
} else {
|
||||
adjustAction('north', 0)
|
||||
adjustAction('south', 0)
|
||||
}
|
||||
//console.log(gp.axes, gp.buttons)
|
||||
let attackHeld = false
|
||||
for (let i = 0; i < 4; i++) {
|
||||
let btn = gp.buttons[i]
|
||||
if (btn.pressed) {
|
||||
attackHeld = true
|
||||
}
|
||||
}
|
||||
if (attackHeld) {
|
||||
adjustAction('attack', 2)
|
||||
} else if (desiredActions.find(v=>v.type==='attack')) {
|
||||
adjustAction('attack', 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let nightfall = (b: boolean) => {
|
||||
|
|
Loading…
Reference in New Issue
Block a user