如何在处理中使用 mousePressed 处理灯光?

How to use mousePressed for lights in processing?

我正在制作有关处理的动画。然后,我有一个关于灯的问题。通常,我的代码比较长。但是,我做了一个简单的代码,对初学者也很有用。

void setup()
{
  size(400, 400, P3D);
  noStroke();
}

void draw()
{
  background(0);
  if (mousePressed) {   // lights should work if the mouse pressed on the sphere
    lights();           // It should continue till press again on the sphere
  }                     // If the mouse pressed again on the sphere, lights should close                            
  translate(200,200,0); // translate the sphere to the middle of window
  sphere(100);          // making a sphere for see ligts
}

所以,正如您在评论中看到的那样。如果鼠标按下球体,灯光应该会亮起,并且它会一直工作,直到鼠标再次按下球体。然后,如果鼠标按下球体,它应该关闭 lights.It 应该一次又一次地工作。如果你知道怎么做。不客气。谢谢

您需要有一个变量来保持灯的状态,并在灯关闭时将其打开或在打开时将其关闭。

这样做之后,在 if 语句中使用 mousePressed 可能会产生一些问题,因为如果点击速度不够快(可能你按下的时间有点长),它会打开然后关闭灯所以它看起来就像从未打开过一样。 为避免这种情况,我建议使用 using mouseReleased() 函数。 这是最终代码:

boolean isOn = false;    // variable keeping the state of the light

void setup()
{
  size(400, 400, P3D);
  noStroke();
}

void draw()
{
  background(0);
  if (isOn)    // checks the state in which the light should be
    lights();
  translate(200,200,0); // translate the sphere to the middle of window
  sphere(100);          // making a sphere for see ligts
}

void mouseReleased() {    // this function is automatically called in draw method
  if (isOn)    //after a click the state of the light is inverted
      isOn = false;
    else isOn = true;
}

无论如何,如果出于某种原因您需要专门使用 mousePressed 函数,她的一些代码也可以工作:

void draw()
{
  background(0);
  if (mousePressed) {   // lights should work if the mouse pressed on the sphere
    if (isOn)
      isOn = false;
    else isOn = true;
    delay(200);    // delay added to minimize the problem explained above
  }                     // If the mouse pressed again on the sphere, lights should close
  if (isOn)
    lights();
  translate(200,200,0); // translate the sphere to the middle of window
  sphere(100);          // making a sphere for see ligts
}