Processing Month, Day 16 - Building a Spaceship
Posted on 2011-05-16 by Jan Vantomme
Tags:
processing, tutorial
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 PVector( width/2, 360 );
point1 = new PVector( location.x , location.y - 20 );
point2 = new PVector( location.x + 10, location.y + 20 );
point3 = new PVector( location.x - 10, location.y + 20 );
}
void update(float x)
{
location.x += x;
location.x = constrain( location.x, 15, width - 15 );
point1.set( location.x , location.y - 20, 0 );
point2.set( location.x + 10, location.y + 20, 0 );
point3.set( location.x - 10, location.y + 20, 0 );
}
void render()
{
fill(0);
stroke(255);
triangle( point1.x, point1.y, point2.x, point2.y, point3.x, point3.y );
}
}
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.update( 10 );
}
}
}
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.
Download
Download the example for Procesing Day 16, Building a Spaceship.