因此,当您按住某个键时,操作系统会有延迟。它将执行一次命令,延迟,然后重复。我试图通过将变量设置为true或false来绕过此,基于密钥何时具有“keydown”和“Keyup”。我不知道为什么它不起作用。我不确定我是否忘记了某些事情,但如果有人能够解释为什么我的代码仍未解决问题。
变量
var keyPressed = {Kleft: 37, Kright: 39, Kup: 38, Kdown: 40, Kspace: 32};
key = {K37: false, K39: false, K38: false, K40: false, K32: false};
检测按下的键
//to detect multiple keys being pressed
$(document).keydown(function(e) {
if(keyPressed.Kleft) //left arrow
{
console.log('test');
key.K37 = true;
airplane.performAction();
}
if(keyPressed.Kright) //right arrow
{
key.K37 = true;
// airplane.performAction();
}
if(keyPressed.Kup) //up arrow
{
key.K37 = true;
// airplane.performAction();
}
if(keyPressed.Kdown) //down arrow
{
key.K37 = true;
// airplane.performAction();
}
if(keyPressed.Kspace) //space key
{
key.K37 = true;
bullet = new Bullet({x: airplane.position.x+32, y: airplane.position.y-12}, bullets_total++); //create a new bullet
bullets.push(bullet); //store the bullet in the bullets array
}
}).keyup(function(e) {
key.K37 = false; //testing just one key for now
console.log('ehhlo');
// console.log(key['K'+toString(e)]);
// key['K'+toString(e)] = false;
});
Keypress上执行的功能
function MyAirplane()
{
this.performAction = function(action)
{
if(key.K37 === true){
console.log('left');
this.position.x -= 10;
}
if(key.K37 == true){
this.position.x += 10;
}
if(key.K37 == true){
this.position.y -= 10;
}
if(key.K37 == true){
this.position.y += 10;
}
}
}
答案 0 :(得分:1)
只是一个想法,尽量不要自动调用performAction。
//to detect multiple keys being pressed
$(document).keydown(function(e) {
if(keyPressed.Kleft) //left arrow
{
key.K37 = true;
}
if(keyPressed.Kright) //right arrow
{
key.K37 = true;
}
if(keyPressed.Kup) //up arrow
{
key.K37 = true;
}
if(keyPressed.Kdown) //down arrow
{
key.K37 = true;
}
if(keyPressed.Kspace) //space key
{
key.K37 = true;
bullet = new Bullet({x: airplane.position.x+32, y: airplane.position.y-12}, bullets_total++); //create a new bullet
bullets.push(bullet); //store the bullet in the bullets array
}
}).keyup(function(e) {
key.K37 = false; //testing just one key for now
console.log('ehhlo');
// console.log(key['K'+toString(e)]);
// key['K'+toString(e)] = false;
});
并创建一个事件计时器:
function MyAirplane()
{
this.performAction = function(action)
{
if(key.K37 === true){
console.log('left');
this.position.x -= 10;
}
if(key.K37 == true){
this.position.x += 10;
}
if(key.K37 == true){
this.position.y -= 10;
}
if(key.K37 == true){
this.position.y += 10;
}
}
// 60 frames per second event checker.
var eventLoop = setInterval(this.performAction.bind(this), 1000 / 60);
}