在我的小型车游戏中,如果我按住" w"关键是汽车向前移动,当我按下" d"钥匙和" w"同时关键,汽车对角移动,但如果我释放了" d"键。汽车应继续前进,但车停了。
我如何解决这个问题?如果我发布了" d"保持" w"按下键,车应该前进。
var twokey = {
d : false,
r : false,
g : false
};
function dig(event){
if ((event.which+32) === 114){ // r
twokey.r = true;
}
else if((event.which+32) === 100){ // d
twokey.d = true;
}
else if((event.which+32) === 103){ // g
twokey.g = true;
}
}
function cod(event){
unicod = event.charCode;
console.log(unicod);
}
var eleme = document.getElementById("limit").getBoundingClientRect();
elemen = document.getElementById("limit");
var unicod = 0;
var etop = eleme.top;
var eleft = eleme.left;
function myMove() {
if(twokey.d && twokey.r){
elemen.style.top = (etop-=6)+'px';
elemen.style.left = (eleft-=6)+'px';
}
else if(twokey.g && twokey.r){
elemen.style.top = (etop-=6)+'px';
elemen.style.left = (eleft+=6)+'px';
}
else{
switch(unicod){
case 114: // r
elemen.style.top = (etop-=6)+'px';
break;
case 100: // d
elemen.style.left = (eleft-=6)+'px';
break;
case 103: // g
elemen.style.left =(eleft+=6)+'px';
break;
case 102: // f
elemen.style.top = (etop+=6)+'px';
break;
}
}
}
function resetob(event){
if (event.which+32 === 114){ // r
twokey.r = false;
console.log("reset r",event.which+32);
}
else if(event.which+32 === 100){ // d
console.log("reset d",event.which+32);
twokey.d = false;
}
else if(event.which+32 === 103){ // g
console.log("reset g",event.which+32);
twokey.g = false;
}
}
}
var body = document.getElementById("bo");
body.addEventListener("keypress",cod);
body.addEventListener("keydown",dig);
body.addEventListener("keyup",resetob);
body.addEventListener("keypress",myMove);