Project 8: Java Programming

Space Wars: Make an applet similar to the Asteroids game.

Here is a hint for getting started. See the package contents as well.

The applet will have the following components:

  1. A canvas in which appears a flying spacecraft. The canvas is mapped "mod 1", so that if the spacescraft flies of an edge, it reenters at the opposite edge.
  2. A panel which controls the booster rockets. Mouse down on the panel fires the boosters and accelerates the spacecraft in the direction it is pointing. Also, it makes a small red flame shoot out the back!
  3. A scroll bar which points the nose of the spacecraft.

The spacecraft flies by inertia, with the rockets adding or subtracting inertia in the direction of the current heading when the boosters are fired. Using a thread, check if the boosters are on, if so, increment the velocity of the spacecraft by a small amount. The current heading should be expressed as (sin theta, cos theta), then the new velocity will be:

       new velocity in x = (old velocity in x) + K1 * (cos theta)
       new velocity in y = (old velocity in y) + K1 * (sin theta)
and update the spacecraft's position:
       new x position = (old x position) + K2 * (velocity in x)
       new y position = (old y position) + K2 * (velocity in y)
where K1 and K2 are fudge factors to make the game dynamics feel correct.

Remember to map back the spacecraft on the canvas. Do do this you might want to consider the canvas coordinates to be from 0.0 to 1.0. The mapping will be taking the fractional part.

You will also need some math to draw the spacecraft in its various orientations. Consider a model of the spacecraft centered on (0,0). Rotate it by rotating each of it's defining vertices around (0,0) by the angle theta. Do this by considering the point (x,y) as a vector and applying the matrix:

        | cos(theta)  -sin(theta) |
        | sin(theta)   cos(theta) |
Then translate the model to be centered on its current screen location (xl, yl). The equation is easy to derive:
        xl + ( x * cos(theta) - y * sin(theta) )
        yl + ( x * sin(theta) + y * cos(theta) )

Copyright 1998 Burton Rosenberg; All rights reserved.