简体   繁体   English

使用 p5.js,在 draw 中使用函数时,如何让它只执行一次?

[英]Using p5.js, when using a function inside of draw, how do I make it only go once?

I'm using p5.js for a project of mine, and I don't understand how I can check if a key is pressed, and when it is, run a function, but only once.我在我的一个项目中使用 p5.js,我不明白如何检查是否按下了某个键,以及何时运行一个函数,但只运行一次。

I have the keyIsDown function inside of draw , because I need to constantly be checking for input, but when a key is pressed, run my function once.我有keyIsDown的函数内部draw ,因为我需要不断地检查输入,但是当有键按下时,运行我的功能一次。 But after this function runs once, I need it to be ready for me to press the key, or a different key, again.但是在此功能运行一次后,我需要它准备好再次按下该键或其他键。

It is currently running the function proportional to the framerate, I want it to run once per key click.它目前正在运行与帧率成正比的函数,我希望它在每次按键点击时运行一次。 Some pseudocode would look like:一些伪代码如下所示:

function ABC () {
    console.log("1")
}

draw () {
    when key(1) is pressed:
        function ABC()
}

And out would output "1" but 5-30 times, even if I click the key as fast as I can.即使我尽可能快地单击该键,out 也会输出“1”但 5-30 次。 The problem is that draw() is constantly looping so when it checks keyPressed , it registers it as pressed a few times.问题是draw()一直在循环,所以当它检查keyPressed ,它会将其注册为按下了几次。

How can I ensure the function only runs once per button click, still continues to wait for another button click, but runs the function work?如何确保每次单击按钮时该功能仅运行一次,仍然继续等待另一次按钮单击,但运行该功能?

EDIT:编辑:

I have tried both:我都试过:

function keyTyped() {
  console.log("a")
  if (key === 'a') {
    console.log("a")
  }
}

and

function keyPressed() {
  console.log("a")
  if (key === 'a') {
    console.log("a")
  }
}

and nothing happens, no matter what key I press.没有任何反应,无论我按什么键。 Something should go to the console, but nothing is.应该有东西进入控制台,但什么都没有。

You could use the keyPressed() function:您可以使用keyPressed()函数:

function draw() {
  // stuff that happens 60 times per second
}

function keyPressed() {
  // stuff that happens once per key press
}

You can find more info in the reference .您可以在参考资料中找到更多信息。

Another approach would be to create a boolean variable that tracks whether you've already handled the key press.另一种方法是创建一个布尔变量来跟踪您是否已经处理过按键操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM