Processing Month, Day 16 - Building a Spaceship

Posted by Jan Vantomme on 16 May 2011.
Tags:

For the next few days, we’ll take a look at designing a game with basic keyboard interaction. Today we’ll focus on drawing a cool spaceship and move it around with the keys. Our spaceship will be a triangle, just like in the arcade classic Asteroids. The code below is the full class for our spaceship. We’ll need a PVector for the location and three for the points of the triangle. We could easily only use the location and draw the triangle from there but those extra points will be useful for collision detection in the next few days.

class SpaceShip
{
    PVector location
;
    
PVector point1;
    
PVector point2;
    
PVector point3;
    
SpaceShip()
    
{
        location 
= new PVectorwidth/2360 );
        
point1 = new PVectorlocation.location.20 );
        
point2 = new PVectorlocation.10location.20 );
        
point3 = new PVectorlocation.10location.20 ); 
    
}
    void update
(float x)
    
{
        location
.+= x;
        
location.constrainlocation.x15width 15 );
        
point1.setlocation.location.20);
        
point2.setlocation.10location.20);
        
point3.setlocation.10location.20);
    
}
    void render
()
    
{
        fill
(0);
        
stroke(255);        
        
trianglepoint1.xpoint1.ypoint2.xpoint2.ypoint3.xpoint3.);
    
}

To move the spaceship, we’ll use the left and right arrow on the keyboard. These are coded keys so we’ll need to check if the keyCode is LEFT or RIGHT. If that is the case, we’ll update the location of the spaceship like this.

void keyPressed()
{
    
if (key == CODED{
        
if (keyCode == LEFT{
            spaceShip
.update( -10 );
        
}
        
if (keyCode == RIGHT{
            spaceShip
.update10 );
        
}
    }

To draw the spaceship to the screen, I’ve used noSmooth() inside draw(). This makes our spaceship looks like it was drawn in the early 80’s, when there was no such thing as antialiasing yet.

void draw()
{
    background
(0);
    
noSmooth();
    
spaceShip.render();

The Spaceship

Our spaceship looks like this. If you did everything right, you can press the left and right keyboard keys to move the spaceship.

A triangular spaceship, built with Processing

Download

Download the example for Procesing Day 16, Building a Spaceship.

Tweet this article