Creating two interactive Arrays and mousePressed Function.

edited October 2013 in Questions about Code

Hello,

I just started working on processing a few weeks ago for my class, and recently was just introduced to arrays. I managed to create a simple array of "bubbles". I am trying to create a fun interactive poster that will have these bubbles with single character of type randomized contained inside each bubble of the array. The catch is that I want to be able to create a mousePressed function to "pop" these bubbles but have the type remain and fall to the bottom of the screen. Any tips would be great or any tutorials that I should be really looking at for this.

//Draw Tab

bubble [] bubbles = new bubble [50];

void setup (){
  size (displayWidth, displayHeight,P2D);
  for (int i = 0; i < bubbles.length; i ++){
    bubbles[i] = new bubble (100);
  }
}

void draw () {
  background (209,230,240);
  for (int i = 0; i < bubbles.length; i ++){
    bubbles [i].display();
     bubbles [i].ascend();
      bubbles [i].top();
 }
}

//Class Tab

class bubble {
  float x, y, yspeed, diameter;

bubble (float tempD){
  x = random (width);
  y = height;
  diameter = tempD;
  yspeed = random (1, 3);

}

void ascend (){
  y = y-yspeed;
  x = x+random(-1,1);

}

void display (){
  stroke (0);
 fill(174,229,250,50);
  ellipse (x,y,diameter,diameter);
  noStroke ();
  fill (255,255,255,75);
  ellipse (x-25,y-20,diameter/5,diameter/5);

}

void top (){
  if (y < diameter/2) {
    y = height;
  }
}
}

Answers

  • mousePressed() must be at the same level than setup() and draw(). So you need to add a mousePressed() method in your class (you can name it differently, it isn't important, the name is local to the class) that you call on each instance of this class from the main mousePressed() function.

    Ie. like you call bubbles[i].display() on each bubble (in a for loop), you must call bubbles[i].pressed() on each bubble inside mousePressed().

    In the pressed() method, you can use dist() between the mouseX / mouseY coordinates and the x, y coordinates of the bubble to see if the click was inside this specific bubble.

Sign In or Register to comment.