(11) A ship that can shoot?

Just to try some other classic games, consider Astroids. In this you are a small ship that looks like a triangle and your objective is to shoot down astroids that are moving around. In the following example, a ship is drawn, pointing to the mouse, and you can shoot bullets. There are no astroids and nothing fancy. There are two new items used.

The first one is the ability in processing to shift the perspective and then shift back. Using this one can draw the same object (like the triangle in the example) the same way, but still make it appear as if it is moving. This is used in the example to both draw the ship and the bullets.

The second new thing, is the use of Objects and list of objects. Objects are used to group variables and code belonging together. It is then also easy to use it over and over without making the code messy. In the example, the bullet is an object. The ship could also have been an object, but it felt too simple.

Enter this and try!

// List of shots
// Shots is an object we have defined that represents a single bullet
ArrayList<shot> shots = new ArrayList<shot>();

// Run once
void setup () {
  frameRate(60);
  size(500, 500);
  // White
  stroke (255);
  fill(255);
}

// Called 60 times per second
void draw()
{
  int i;
  // Find the angle from x=250, y=250 to the mouse
  float angle = atan2(mouseY - 250, mouseX - 250);

  // Clear screen, black
  background(0);
  // "pushMatrix" saves current viewpoint
  pushMatrix();
  // Set 250,250 as the new 0,0 
  translate(250, 250);
  // Rotate screen "angle" 
  rotate(angle);
  // Draw a triangle (the ship)
  triangle(20, 0, -20, -10, -20, 10);
  // Bring back normal perspektive
  popMatrix();
  // Go through all shots (if any) and update their position
  for (i = 0; i<shots.size(); i++) {
    shot s = shots.get(i);
    if (s.update()) {
      // Remove bullet, if outside screen
      shots.remove(i);
    }
  }
}

// When left mouse button is pressed, create a new shot
void mousePressed() {
  if (mouseButton == LEFT) {
    float angle = atan2(mouseY - 250, mouseX - 250);
    shots.add(new shot(angle, 2));
  }
}

// Class definition for the shot
class shot {
  // A shot has x,y, and speed in x,y. All float for smooth movement
  float angle, speed;
  float position;

  // Constructor  
  shot(float _angle, float _speed) {
    angle = _angle;
    speed = _speed;
    position = 0;
  }

  // Update position, return true when out of screen
  boolean update() {
    position = position + speed;
    pushMatrix();
    // Set 250,250 as the new 0,0 
    translate(250, 250);
    // Rotate screen "angle" 
    rotate(angle);
    // Draw bullet
    ellipse (position + 20, 0, 5, 5);
    // Bring back normal perspektive
    popMatrix();
    if (position>250) {
      return true;
    } else {
      return false;
    }
  }
}




No comments:

Post a Comment