Processing Month, Day 17- Falling Asteroids

Posted on 2011-05-17 by Jan Vantomme
Tags: processing, tutorial

Today will be about animating asteroids and setting up the basic scoreboard for our little game. The Asteroids class looks almost the same as the Bubbles class from Day 8. One key difference is that we'll update the scoreboard when the asteroids go off-screen. That, and the fact that the asteroids go down, while the bubbles went up.

class Asteroid
{
    PVector location;
    float   speed;
    float   radius;
    Asteroid()
    {
        location = new PVector( random( width ), -20 );
        speed = random( 1, 2 );
        radius = random( 10, 20 );
    }
    void update()
    {
        location.y += speed;
        if (location.y >= height + radius) {
            reset();
            score++;
         }
    }
    void render()
    {
        fill(0);
        stroke(255, 0, 0);
        pushMatrix();
        translate( location.x, location.y );
        ellipse( 0, 0, radius * 2, radius * 2 );
        popMatrix();
    }
    void reset()
    {
         location.x = random(width);
         location.y = -20;
         speed = random( 1, 2 );
         radius = random( 10, 20 );
    }
}

Another difference is that we'll use an ArrayList to keep track of our Asteroid objects. This will be more flexible than the Array we used in our Bubble sketch. You can easily add or remove objects from an ArrayList. If we declare the ArrayList like this, we'll be able to use a really clean for-loop to update our objects and draw them to the screen.

ArrayList<Asteroid> asteroids;

Note that we use the add() method on our ArrayList object to add new Asteroid objects. This piece of code goes in setup().

asteroids = new ArrayList<Asteroid>();
for (int i = 0; i < 10; i++) {
   asteroids.add( new Asteroid() );
}

To draw the asteroids to the screen, type this piece of code inside draw(), before drawing the spaceship. Notice how clean the for-loop is?

for (Asteroid a : asteroids ) {
    a.update();
    a.render();   
}

We also need to declare a variable to keep track of our score. We'll use an integer and set it to 0. To draw the scoreboard to the screen, we need to use the text() function. It's best that we draw the interface on top of all other things so this one goes at the end of draw(). I'm using the nf() function to format the score so it always has 5 digits.

fill(255);
text("SCORE: " + nf(score, 5), 225, 20 );

Documentation

Download

Download the sketch for Processing Month, Day 17 - Falling Asteroids.

Tweet this article