Daymnn
Daymnn

Reputation: 229

How to use mousePressed for lights in processing?

I was working on an animation on processing. Then, I have a question about the lights. Normally, my code is more long. However, I made a simple code which can usefull also for the beginners.

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
}

So, as you can see on the comments. If the mouse pressed on the sphere the lights should work and it should keep working till the mousepressed again on the sphere. Then, if mouse pressed on the sphere it should close the lights.It should keep working again and again. If you know how to make it. You are welcome. Thanks.

Upvotes: 2

Views: 318

Answers (1)

ssoBAekiL
ssoBAekiL

Reputation: 635

You need to have a variable that keeps the state of the light and switch it on if it's off or switch it off if it's on.

After doing that, using mousePressed in the if statement might create some problems since if the click is not quick enough (maybe you press for a bit too long) it will turn on and then off the light so it will look like it was never turned on. To avoid that I suggest using mouseReleased() function. Heres the final code:

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

Anyway if for some reason you needed to use specifically mousePressed function her's some code also working:

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
}

Upvotes: 2

Related Questions