简体   繁体   中英

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.

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. 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. The problem is that draw() is constantly looping so when it checks keyPressed , it registers it as pressed a few times.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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