keydown长按时短暂卡顿问题

keydown 属于键盘事件(Keyboard Events),当键盘按下某个按键时触发,且默认情况下,长按某按键会重复触发。但事件会判断用户是否长按还是连续按下,因此会有一定延迟(有点类似移动端适配时onclick事件会有300ms延迟)。一般情况下该延迟很难察觉,但在开发JS游戏时,发现该延迟会严重降低游戏体验,给玩家一种十分卡顿的感觉。此时就很有必要解决该问题。

不废话,先看代码逻辑:

Game 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function Game () {
this.bindEvent();
this.start();
this.plane = new Plane();
}
//监听事件函数
Game.prototype.bindEvent = function () {
//这里使用JQuery方法获取DOM
$(document).keydown(function(event){
var event = event || window.event;
if(event.keyCode == 37) {game.plane.left();}
else if(event.keyCode == 39) {game.plane.right();}
})
}
//主循环函数
Game.prototype.start = function () {
var timer = setInterval(function(){
game.plane.render();
})
}

Plane 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Plane.prototype.render = function () {
game.ctx.drawImage(this.plane,this.x,game.canvas.height - 124 - 20);
}
//飞机左移
Plane.prototype.left = function () {
this.x -=5;
if(this.x <= 0){
this.x = 0;
}
}
//飞机右移
Plane.prototype.right = function () {
this.x +=5;
if(this.x >= game.canvas.width - 100){
this.x = game.canvas.width - 100;
}
}

throttledebounce 是解决请求和响应速度不匹配问题的两个方案。二者的差异在于选择不同的策略。

参考

本文完。

© 2019 lvbin's Blog All Rights Reserved.
Theme by hiero