JavaScript 移动延迟和多次击键
JavaScript move delay and multiple keystrokes
这是我的问题:http://testepi.kvalitne.cz/test/
我不想要按键和正方形移动之间的延迟。我还想知道如何对角线移动(同时按两个键)。
我的代码:
$(function(){
document.addEventListener("keydown", move, false);
var x = 0;
var y = 0;
function move(event){
if(event.keyCode==37){
x -= 10;
$("#square").css("left", x);
}
if(event.keyCode==39){
x += 10;
$("#square").css("left", x);
}
if(event.keyCode==38){
y -= 10;
$("#square").css("top", y);
}
if(event.keyCode==40){
y += 10;
$("#square").css("top", y);
}
}
});
首先,为了避免按键/重复延迟,您必须将程序包装在一个循环中,并使键盘的状态在该循环范围内可用,其次,要监视多个按键,您需要跟踪各个按键和键操作事件:
var x = 0;
var y = 0;
// store the current pressed keys in an array
var keys = [];
// if the pressed key is 38 (w) then keys[38] will be true
// keys [38] will remain true untill the key is released (below)
// the same is true for any other key, we can now detect multiple
// keypresses
$(document).keydown(function (e) {
keys[e.keyCode] = true;
});
$(document).keyup(function (e) {
delete keys[e.keyCode];
});
// we use this function to call our mainLoop function every 200ms
// so we are not relying on the key events to move our square
setInterval( mainLoop , 200 );
function mainLoop() {
// here we query the array for each keyCode and execute the required actions
if(keys[37]){
x -= 10;
$("#square").css("left", x);
}
if(keys[39]){
x += 10;
$("#square").css("left", x);
}
if(keys[38]){
y -= 10;
$("#square").css("top", y);
}
if(keys[40]){
y += 10;
$("#square").css("top", y);
}
}
如果你正在尝试实现类似游戏的2d精灵移动,我建议你有一个x和y速度的概念,而不是在按键时移动固定数量的精灵。
因此,在按键时,从 x 或 y 速度中添加或减去。
var xvel = 0,
yvel = 0,
x = 0,
y = 0;
setInterval(function () {
y += yvel;
x += xvel;
$("#square").css("left", x);
$("#square").css("top", y);
}, 16); //run an update every 16 millis
document.addEventListener("keydown", move, false);
function move(event){
if(event.keyCode==37){
xvel -= 10;
}
if(event.keyCode==39){
xvel += 10;
}
if(event.keyCode==38){
yvel -= 10;
}
if(event.keyCode==40){
yvel += 10;
}
}
但是,您还需要担心键控事件,因为速度会一直保持到您将其取消为止。
您可以使用setInterval
每x毫秒更新一次角色的位置。(游戏滴答声)
要对角线移动,只需同时增加/减去 x 和 y 的速度。
这只是一个例子,但还有更多关于精灵运动的例子。
你看过这里吗? 您应该能够通过检查是否按下了多个键而不释放来进行对角线移动。
相关文章:
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- 正在SharePoint 2013母版页中添加JQuery移动文件
- 如何在android中使用phonegap将文件从一个文件夹移动/复制到另一个文件夹
- 如何使用phaser使html5游戏在移动设备浏览器上运行
- FabricJs-限制主对象内添加对象的移动区域
- 如何减少在移动网络应用程序上播放声音的延迟
- 移动设备上的 HTML 5 音频 .play() 延迟
- 在定时器/延迟的画布上移动不同的图像
- JavaScript 移动延迟和多次击键
- 如何无延迟地处理 100 多个移动矩形
- 在大多数移动浏览器上,图像仅在出现重大延迟后才会更改
- JavaScript DOM 在 touchmove 中的更改延迟到移动 Safari 上的滚动结束
- 在移动浏览器上播放 HTML5 音频文件时出现延迟
- Raphael JS:延迟后沿着路径移动图像
- 移动Safari (iPhone)对Javascript GET请求有30秒以上的延迟
- 在移动设备上使用jcarousel框架时,在pageshow()事件上延迟几秒钟
- 触摸移动和触摸启动以及300ms延迟
- 如何调整Mootools拖动.移动类,使其在px中没有初始延迟
- 移动设备中的滚动事件触发延迟
- 视差脚本在chrome和移动设备上延迟