Project - Asteroids
Part 3 - The Spaceship moves
Now that we've got a spaceship on screen, let's get it to move.
3.1. Reset the screen size
The default window size in Processing is very small. Set up a more reasonably-sized window for the game using the size() command in the setup() method of your AsteroidsGame.pde.
3.2. Checking for keyPressed
Recall that the draw() method in Processing loops infinitely, executing instructions repeatedly, and listening for events from the user, including mouse movement, mouse clicks, and keypresses.
Let's get the ship to respond to keypresses so we can control it.
- Your ship probably doesn't have a velocity yet. Even if it did, it wouldn't yet be moving because we haven't called the move() method yet. In the draw() method of AsteroidsGame.pde, include a line that calls the spaceship's move() method, just before it gets drawn.
Without a velocity, it still won't be moving, though. Let's fix that.
- In AsteroidsGame.pde, add a new method public void keyPressed():
/**
* The keyPressed listener is checked every time the
* draw() method runs, to see if a key has been pressed.
*/
public void keyPressed()
{
if (key == 's') // key is of type char,
// which uses single quotes
{
s.accelerate(3); // speed up the spacecraft in
// whichever direction it's
// currently pointing
}
}
- Okay, our ship is moving, but it's leaving a trail of previous ship positions on the screen. We need to clear the screen of everything that's on it before we move and draw the ship.
In the draw() loop, let's include a background(0) to give our screen an appropriately space-y black background.
Although this will have the effect of wiping out everything that we've drawn on the screen previously, we'll be re-drawing everything—the spaceship, the star zoos, the moving asteroids, etc.—every time we run through the draw look, and it's fast enough that we won't notice the effect.
- Once your spaceship is able to accelerate across the screen, add additional if statements into the keyPressed() method for turning left and turning right.
Next...
Part 4 - Make some Asteroid objects