How to make something happen when a key is held down in p5.js

偶尔善良 提交于 2020-08-10 01:10:29

问题


I'm trying to make a simple drawing program where the color and size of the line being drawn changes when the 'e' key is held down. However, when I try to use keyPressed, it only executes once, resulting in a single blue dot being drawn instead of changing the whole line. Basically, what I need to know is how to make something happen when a key is held, because it only registers the press once. This is what I have so far:

    function keyTyped() {
      if (key === 'e') {
        if (mouseY < 417) {
          fill(0,0,255,100);
          ellipse(mouseX,mouseY,5,5);
        }
      }
    }

instead of

   function draw() {
     if (mouseY < 417) {
       noStroke();
       fill(0,100);
       ellipse(mouseX,mouseY,20,20);
     }
   }

回答1:


You could just check from the draw() function, like this:

function draw() {
  if (keyIsPressed && key == 'e') {
    noStroke();
    fill(0,100);
    ellipse(mouseX,mouseY,20,20);
  }
}

Or you could create a variable that tracks whether the key is being pressed. Set it to true from the keyPressed() function, and set it to false in the keyReleased() function. Then check the variable in the draw() function.

More info can be found in the reference.



来源:https://stackoverflow.com/questions/46351604/how-to-make-something-happen-when-a-key-is-held-down-in-p5-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!