如何在JS中使用空格键和if语句? [英] How to use spacebar and if statements in JS?

查看:104
本文介绍了如何在JS中使用空格键和if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于 http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/ 它进展顺利,但我想制作一个函数来读取两个项目是否是触摸仅在按下空格键时发生。

I am making a game based off of a tutorial at http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/ it is going well but I wanted to make the function that reads if the two items are touching only happen when the space bar is pressed.

if (hero.x <= (monster.x + 32)
    && monster.x <= (hero.x + 32)
    && hero.y <= (monster.y + 32)
    && monster.y <= (hero.y + 32)) {
  ++monstersCaught;
  reset();
}

if (hero.x <= (tack.x + 32)
    && tack.x <= (hero.x + 32)
    && hero.y <= (tack.y + 32)
    && tack.y <= (hero.y + 32)) {
  monstersCaught -= monstersCaught;
  reset();
}

if (monstersCaught > 10) {
  monstersCaught -= 10;
}

我应该如何解决

if (hero.x <= (tack.x + 32)
    && tack.x <= (hero.x + 32)
    && hero.y <= (tack.y + 32)
    && tack.y <= (hero.y + 32)) {
  monstersCaught -= monstersCaught;
  reset();
}

这样只有在空格键被按下时才会出现?

so that it only goes if the space bar is pressed?

推荐答案

最简单的方法是随时了解键盘的状态:为此你必须听取键盘事件并更新包含每个键的状态。

Most easy way is to know at any moment the status of your keyboard : for that you have to listen to keyboard events and update an array containing the status of each key.

这将导致类似:

window.keyStates = [];   // now you can use keyStates anywhere. 
                       // good enough since you seem to be in the first steps.

window.addEventListener('keydown',
          function(e) { keyStates[e.keyCode || e.key] = true;} );

window.addEventListener('keyup', 
          function(e) { keyStates[e.keyCode || e.key] = false;} );

完成后,您可以随时随地测试空格键的状态:

Once you have done that, you can test anywhere, anytime, the status of the space key with :

if (keyStates[32] == true) { ... }

为了便于阅读,您可能更喜欢定义一个密钥对象来保存您使用的几个密钥代码:

you might prefer, for readability, define a key object that will hold the few keycodes you use :

window.key = {
     space : 32,
     enter : 13,
     left  : 37,
     up    : 38,
     right : 39,
    down : 40
}

这样,你可以写:

if ( keyStates[key.space] == true ) {  
     ... 
} 

更容易理解。

(Rq:如果你搜索密钥代码,看这里是一种方式: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

(Rq : if you search for keycodes, looking here is one way : https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent )

这篇关于如何在JS中使用空格键和if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆