Processing Month, Day 17- Falling Asteroids

Posted by Jan Vantomme on 17 May 2011.
Tags:

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 PVectorrandomwidth ), -20 );
        
speed random1);
        
radius random1020 );
    
}
    void update
()
    
{
        location
.+= speed;
        if (
location.>= height radius{
            reset
();
            
score++;
         
}
    }
    void render
()
    
{
        fill
(0);
        
stroke(25500);
        
pushMatrix();
        
translatelocation.xlocation.);
        
ellipse00radius 2radius );
        
popMatrix();
    
}
    void reset
()
    
{
         location
.random(width);
         
location.= -20;
         
speed random1);
         
radius random1020 );
    
}

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<Asteroidasteroids

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 010i++) {
   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(score5), 22520 ); 

Documentation

Download

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

Tweet this article