【问题标题】:How to use mousePressed for lights in processing?如何在处理中使用mousePressed进行灯光?
【发布时间】:2020-05-31 09:43:20
【问题描述】:

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

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
}

所以,正如您在 cmets 上看到的那样。如果鼠标按在球体上,灯应该工作,它应该继续工作,直到鼠标再次按在球体上。然后,如果鼠标按在球体上,它应该关闭灯。它应该一次又一次地继续工作。如果你知道怎么做。不客气。谢谢。

【问题讨论】:

    标签: java processing


    【解决方案1】:

    您需要有一个变量来保持灯的状态,如果它关闭则将其打开,如果它打开则将其关闭。

    这样做之后,在 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
    }
    

    【讨论】:

    • @ssBAekiL 我想问你一些事情。实际上,我注意到,如果我在球体外部按下鼠标按钮,它仍然可以工作。但是,我只希望它“在球体上工作”这可能吗?
    • 您还需要这方面的帮助吗?看起来你在另一个帖子中得到了答案,对吧?
    • 谢谢@ssoBAekiL,这很紧急。这就是我开新帖的原因。我得到了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2011-09-06
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多