我试图开发一个JavaScript游戏引擎,我遇到了这个问题:
当我按空格键时,角色会跳跃。 当我按下→角色向右移动。
问题是,当我按右键,然后按空格键时,角色会跳跃,然后停止移动。
我使用keydown函数来按下键。如何检查是否同时按下了多个键?
我试图开发一个JavaScript游戏引擎,我遇到了这个问题:
当我按空格键时,角色会跳跃。 当我按下→角色向右移动。
问题是,当我按右键,然后按空格键时,角色会跳跃,然后停止移动。
我使用keydown函数来按下键。如何检查是否同时按下了多个键?
当前回答
Easiest, and most Effective Method
//check key press
function loop(){
//>>key<< can be any string representing a letter eg: "a", "b", "ctrl",
if(map[*key*]==true){
//do something
}
//multiple keys
if(map["x"]==true&&map["ctrl"]==true){
console.log("x, and ctrl are being held down together")
}
}
//>>>variable which will hold all key information<<
var map={}
//Key Event Listeners
window.addEventListener("keydown", btnd, true);
window.addEventListener("keyup", btnu, true);
//Handle button down
function btnd(e) {
map[e.key] = true;
}
//Handle Button up
function btnu(e) {
map[e.key] = false;
}
//>>>If you want to see the state of every Key on the Keybaord<<<
setInterval(() => {
for (var x in map) {
log += "|" + x + "=" + map[x];
}
console.log(log);
log = "";
}, 300);
其他回答
如果有人需要简单的解决方案。
let keys = [];
document.addEventListener("keydown", (e) => {
keys.push(e.key);
if (keys.includes("Control") && keys.includes("o")) {
console.log("open");
}
if (keys.includes("Control") && keys.includes("s")) {
console.log("save");
}
});
// clear the keys array
document.addEventListener("keyup", () => {
keys = [];
});
只是让某些东西更稳定:
var keys = [];
$(document).keydown(function (e) {
if(e.which == 32 || e.which == 70){
keys.push(e.which);
if(keys.length == 2 && keys.indexOf(32) != -1 && keys.indexOf(70) != -1){
alert("it WORKS !!"); //MAKE SOMETHING HERE---------------->
keys.length = 0;
}else if((keys.indexOf(32) == -1 && keys.indexOf(70) != -1) || (keys.indexOf(32) != -1 && keys.indexOf(70) == -1) && (keys.indexOf(32) > 1 || keys.indexOf(70) > 1)){
}else{
keys.length = 0;
}
}else{
keys.length = 0;
}
});
我会试着在按键时添加一个按键事件处理程序。例句:
window.onkeydown = function() {
// evaluate key and call respective handler
window.onkeypress = function() {
// evaluate key and call respective handler
}
}
window.onkeyup = function() {
window.onkeypress = void(0) ;
}
这只是为了说明一个模式;这里我就不详细介绍了(尤其是浏览器特定的level2+事件注册)。
请回复这是否有帮助。
这不是一个通用的方法,但在某些情况下是有用的。这是有用的组合,如CTRL + something或Shift + something或CTRL + Shift + something,等。
示例:当您想使用CTRL + P打印页面时,第一个按下的键总是CTRL + P, CTRL + S, CTRL + U和其他组合也是如此。
document.addEventListener (keydown,函数(e) { //SHIFT +某个值 如果(e.shiftKey) { 开关(e.code) { 例“钥匙”: console.log('Shift + S'); 打破; } } //CTRL + SHIFT +一些 如果(e。&& e.shiftKey){ 开关(e.code) { 例“钥匙”: console.log('CTRL + Shift + S'); 打破; } } });
使keydown甚至调用多个函数,每个函数检查特定的键并适当地响应。
document.keydown = function (key) {
checkKey("x");
checkKey("y");
};