当您点击另一个窗口并返回时,Canvas会自动运行。
我添加了关键听众,当您点击w
a
s
d
或up
,left
时,他们会移动船只, right
,down
。
一切正常,直到您单击向上和向右两个按钮,然后单击另一个选项卡或窗口然后返回。然后它会继续移动而不是听你的输入。
我认为问题在于,当您点击页面时,画布永远不会检查是否关闭了键。但是,当您点击屏幕时,如何使所有键的行为都像是未按下的那样? 当你离开屏幕时,敌人也消失了 这是按下按钮时发生的情况:
Player.prototype.checkKeys = function() //these functions are in the PLayer class
{
if(this.isUpKey == true)//if true
{
if(Player1.drawY >= 0)
{
this.drawY -= this.Speed;
}
}
if(this.isRightKey == true)
{
if(Player1.drawX <= (canvasWidthShips - this.playerWidth))
{
this.drawX += this.Speed;
}
}
if(this.isDownKey == true)
{
if(Player1.drawY <= (canvasHeightShips - this.playerHeight))
{
this.drawY += this.Speed;
}
}
if(this.isLeftKey == true)
{
if(Player1.drawX >= 0)
{
this.drawX -= this.Speed;
}
}
};
这些是我检查按键何时按下的简单功能,我不认为错误在这里但不确定?
function checkKeyDown(e)
{
if (Paused == false)
{
var KeyID = e.KeyCode || e.which;
if (KeyID === 38 || KeyID === 87) //up and w keyboard buttons
{
Player1.isUpKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 39 || KeyID === 68) //right and d keyboard buttons
{
Player1.isRightKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 40 || KeyID === 83) //down and s keyboard buttons
{
Player1.isDownKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 37 || KeyID === 65) //left and a keyboard buttons
{
Player1.isLeftKey = true;
e.preventDefault(); //webpage dont scroll when playing
}
}
else if (Paused == true)
{
Player1.isUpKey = false;
Player1.isDownKey = false;
Player1.isRightKey = false;
Player1.isLeftKey = false;
}
}
function checkKeyUp(e)
{
if (Paused == false)
{
var KeyID = e.KeyCode || e.which;
if (KeyID === 38 || KeyID === 87) //up and w keyboard buttons
{
Player1.isUpKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 39 || KeyID === 68) //right and d keyboard buttons
{
Player1.isRightKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 40 || KeyID === 83) //down and s keyboard buttons
{
Player1.isDownKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
if (KeyID === 37 || KeyID === 65) //left and a keyboard buttons
{
Player1.isLeftKey = false;
e.preventDefault(); //webpage dont scroll when playing
}
}
else if (Paused == true)
{
Player1.isUpKey = false;
Player1.isDownKey = false;
Player1.isRightKey = false;
Player1.isLeftKey = false;
}
}
答案 0 :(得分:0)
暂停比赛可以吗?您可以在浏览器窗口上侦听onblur
,当它失去焦点时会触发,然后在事件处理程序中暂停游戏。
window.onblur = function() {
// Add logic to pause the game here...
Paused = true;
};