Processing Month, Day 8 - Animating Bubbles

Posted by Jan Vantomme on 08 May 2011.
Tags:

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
.-= speed;

To view the animation, you’ll need to change the for-loop inside draw() to this:

for (int i 0bubbles.lengthi++) {
    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
.random(width);
    
loc.height 50;
    
speed random(0.52);
    
radius random510 );

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 0bubbles.lengthi++) {
    bubbles[i]
.update();
    
bubbles[i].render();
    if ( 
bubbles[i].loc.< -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.

Sketch for Processing Month, Day 8.

Tweet this article