Having trouble switching scenes using mousePressed function

Hi, im new to processing and the forums, i'm having difficulty making my scene switch when the mouse button is pressed. My sketch isn't complicated, i have three scenes each one with a mixture of squares and circles and i want the scene to change when the mouse is pressed. I am really stomped as i can't see anything wrong with my code, and was hoping if someone more experienced could see what was wrong.

here is my code

int scene = 0;

float centX, centY;

//colour palette
color c1 = color(38,43,54); //dark blue/grey
color c2 = color(145,121,96); //peachy colour
color c3 = color(214,207,199); // beige colour
color c4 = color(199,179,113); //yellowy colour

void setup(){
size(640, 360);
background(c1);
smooth(8);
noFill();
//noStroke();
//strokeWeight(3);
centX=width/2;
centY=height/2;
//ellipseMode(CENTER);
rectMode(CENTER);
}

void draw(){
  if(mousePressed) {
    scene++;
  }
}


void drawScene(){
  switch(scene){
    case 0:
      stroke(c2);
      ellipse(centX-160,centY,100,100);
      stroke(c3);
      ellipse(centX,centY,100,100);
      stroke(c4);
      ellipse(centX+160,centY,100,100);
      break;
    case 1:
      stroke(c2);
      rect(centX-160,centY,100,100);
      stroke(c3);
      ellipse(centX,centY,100,100);
      stroke(c4);
      ellipse(centX+160,centY,100,100);
      break;
    case 2:
      stroke(c2);
      ellipse(centX-160,centY,100,100);
      stroke(c3);
      rect(centX,centY,100,100);
      stroke(c4);
      ellipse(centX+160,centY,100,100);
      break;
    case 3:
      stroke(c2);
      ellipse(centX-160,centY,100,100);
      stroke(c3);
      ellipse(centX,centY,100,100);
      stroke(c4);
      rect(centX+160,centY,100,100);
      break;
  }
}

any help would be very appreciated

Tagged:

Answers

  • edited October 2014 Answer ✓

    You should use the mousePressed() function instead of the boolean mousePressed. Replace lines 25 to 27 with "drawScene();" and add:

    void mousePressed(){
      scene++;
      scene%=4;
    }
    
  • thanks TFGuy44, took me a while but i got it to work. Do you mind explaining what i had did wrong, as it would really help me understand.

  • Well, draw() runs continuously to update the sketch, usually about 60 times a second. So if you have the mouse pressed down for, say, even half a second in your original code, you're going to do scene++ ~30 times! That's not what you want at all!

    Instead, there's a mousePressed() function that runs just ONCE when the mouse is pressed, each time it is pressed. Doing scene++ in that function is only going to increase the scene variable once per click, you see? The line "scene%=4;" makes it wrap around back to 0 when it hits 4, since you only have 4 scenes.

  • I see, thanks alot for your help, i can understand why it went wrong now

Sign In or Register to comment.