Processing Month, Day 8 - Animating Bubbles
Posted on 2011-05-08 by Jan Vantomme
Tags:
processing, tutorial
To animate the bubbles we made yesterday, we'll need to add a new method to our Bubble class: the update()
method. If we call this method before we call the render()
method on our bubble objects inside draw()
, the y-position of the bubble will change, and the bubble will be rendered on a new coordinate. The update method looks like this:
void update()
{
loc.y -= speed;
}
To view the animation, you'll need to change the for-loop inside draw() to this:
for (int i = 0; i < bubbles.length; i++) {
bubbles[i].update();
bubbles[i].render();
}
A second problem we have now is that when the bubbles go off-screen, we don't see them anymore, and we end up with an empty screen. That's why we'll add a reset method to our Bubble class. This method will reset the location, speed and radius of the bubble once it is not visible anymore. Add this method to the Bubble class:
void reset()
{
loc.x = random(width);
loc.y = height + 50;
speed = random(0.5, 2);
radius = random( 5, 10 );
}
To check if the bubble is not visible anymore, we'll add an if-statement to check if the y-coordinate of the location of the bubble is less than -50. If it is, we'll call the reset()
method on that specific Bubble object. The final function in draw()
should look like this:
for (int i = 0; i < bubbles.length; i++) {
bubbles[i].update();
bubbles[i].render();
if ( bubbles[i].loc.y < -50) {
bubbles[i].reset();
}
}
Download
Download today's sketch to see the full source and play around with it. If you want to see what the final sketch looks like, I've added it to OpenProcessing.