Quantcast
Channel: Dark Views » Games
Viewing all articles
Browse latest Browse all 21

Writing Games with Processing: Enemies

$
0
0

The next element of our game are the crocodiles. Since we can have several of them, let’s use a class to collect all data necessary to draw them:

class Enemy {
  color c;
  int x, y;
  String name;
  
  Enemy(String name) {
    this.name = name;
    c = color(222,40,107);
  }
  
  void draw() {
    fill(c);
    ellipse(x + tileSize/2, y + tileSize/2, tileSize, tileSize);
    
    fill(0);
    textAlign(CENTER, TOP);
    textSize(12);
    text(name, x + tileSize/2, y + tileSize + 2);
  }
}

As you can see, the code is pretty similar to the drawing Platty, the player character. I’m giving them names to make it easier to distinguish them on the screen and while debugging.

Next, we need a list of enemies and a helper function to easily create enemies:

ArrayList<Enemy> enemies = new ArrayList<Enemy>();
void addEnemy(int x, int y, String name) {
  Enemy enemy = new Enemy(name);
  enemy.x = x;
  enemy.y = y;
  enemies.add(enemy);
}

To draw them, we just loop over the elements in the list and call the draw() method of each element:

void drawEnemies() {
 for(Enemy e: enemies) {
    e.draw();
  }
}

Next, we add two enemies in the initial setup:

void setup() {
  size(640, 480); //VGA for those old enough to remember
  
  addEnemy(20, 20, "Kenny");
  addEnemy(600, 20, "Benny");
}

After adding the new drawEnemies() method to draw(), we’re done:

void draw() {
  drawBackground();
  drawPlatty();
  drawEnemies();
}

Let’s see what we’ve got:

RunPlattyRun_V2

You can find the final code here.

Next: Moving around
Previous: Setup and a Simple Player Character
First post: Getting Started


Tagged: Game, Games, Processing

Viewing all articles
Browse latest Browse all 21

Trending Articles