计时器用完时禁用运动

disable movement when timer runs out

我正在学习使用 javascript 在 html canvas 中制作格斗游戏的教程,但我想更改一些内容,我只能更改一部分弄清楚,这就是当计时器归零时冻结玩家的方法。有人有什么想法吗?

let timer = 10
let timerId
function decreaseTimer(){
    if(timer > 0) {
        timerId = setTimeout(decreaseTimer, 1000)
        timer--
        document.querySelector('#timer').innerHTML = timer
         
    }
    if(timer === 0){
        determineWinner({player, enemy, timerId})
       // freeze player
        
    } 
}

移动分别定义为player.velocity.x/y

也像这样使用 keydown:

window.addEventListener ('keydown', (event) => {
    switch (event.key) {
        case 'd':
            keys.d.pressed = true
            player.lastKey = 'd'
        break
        case 'a':
            keys.a.pressed = true
            player.lastKey = 'a'
        break
        case 'w':
            keys.w.pressed = true
                player.velocity.y = -10
        break

        case ' ':
            player.attack()
        break

        case 'ArrowRight':
            keys.ArrowRight.pressed = true
            enemy.lastKey = 'ArrowRight'
        break
        case 'ArrowLeft':
            keys.ArrowLeft.pressed = true
            enemy.lastKey = 'ArrowLeft'
        break
        case 'ArrowUp':
            
                enemy.velocity.y = -10
        break
        case 'Enter':
            enemy.attack()
    }
    
})

window.addEventListener ('keyup', (event) => {
    switch (event.key) {
        case 'd':
            keys.d.pressed = false
        break
        case 'a':
            keys.a.pressed = false
        break
        case 'w':
            keys.w.pressed = false
        break

        case 'ArrowRight':
            keys.ArrowRight.pressed = false
        break
        case 'ArrowLeft':
            keys.ArrowLeft.pressed = false
        break
        case 'ArrowUp':
            keys.ArrowUp.pressed = false
        break
    }
})

'freezing the player'有多种方式。其中一些更好,具体取决于您暂停/玩游戏的方式。

  • 您可以将移动逻辑更改为仅在 timer > 0
  • 时移动玩家
  • 您可以将速度设置为 0 并且不更新速度
  • 停止所有player-moving逻辑