2013-06-03 29 views
0

当您单击另一个窗口并返回时,Canvas会自动运行。画布自动运行关闭窗口点击?

我增加了关键的听众和他们做当你点击wasdupleftrightdown船的举动。

它一切正常,直到你点击向上和向右的两个按钮,然后点击另一个选项卡或窗口并返回。然后它会继续移动而不听你的输入。

我认为问题在于,当你点击页面时,画布永远不会检查钥匙是否被留下。但是如何让所有钥匙的动作就像他们未按下时一样屏幕? 能敌disappera,当你移动关闭屏幕 这是当按下按钮会发生什么:

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

暂停游戏可以吗?您可以在浏览器窗口上侦听onblur,当它失去焦点时触发,然后在事件处理程序中暂停游戏。

window.onblur = function() { 
       // Add logic to pause the game here... 
       Paused = true; 
      }; 
+0

这有效,但我怎么能不停止它我不想点击画布恢复?有没有窗户的窗户? – Barney

+0

是的,有:'window.onfocus'与'window.onblur'相反 – Hendrik