在p5.js中按住键时如何使事情发生 [英] How to make something happen when a key is held down in p5.js

查看:112
本文介绍了在p5.js中按住键时如何使事情发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的绘图程序,在按住e键的同时,绘制的线条的颜色和大小也会发生变化。但是,当我尝试使用 keyPressed 时,它只执行一次,导致绘制了一个蓝点,而不是改变整行。基本上,我需要知道的是在按住某个键时如何使某件事发生,因为它只注册一次按键。到目前为止,这是我所拥有的:

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);
        }
      }
    }

而不是

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


推荐答案

您可以只通过 draw()函数进行检查,就像这样:

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);
  }
}

或者您可以创建一个变量来跟踪键被按下。从 keyPressed()函数将其设置为 true ,并将其设置为 false keyReleased()函数中的code>。然后在 draw()函数中检查变量。

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.

更多信息可在参考

这篇关于在p5.js中按住键时如何使事情发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆