Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - 使用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.(即使我尽可能快地单击该键,输出也将输出“ 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(另一种方法是创建一个布尔变量,以跟踪您是否已经处理过按键。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...