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.(即使我尽可能快地单击该键,输出也将输出“ 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.(东西应该进入控制台,但是什么也没有。)
ask by joelanbanks3 translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…