Processing Month, Day 16 - Building a Spaceship

Posted by Jan Vantomme on 16 May 2011.

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;
= new PVectorwidth/2360 );
point1 = new PVectorlocation.location.20 );
point2 = new PVectorlocation.10location.20 );
point3 = new PVectorlocation.10location.20 ); 
    void update
(float x)
.+= x;
location.constrainlocation.x15width 15 );
    void render

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{
.update( -10 );
if (keyCode == RIGHT{
.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()

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 the example for Procesing Day 16, Building a Spaceship.

Tweet this article