Writing Games with Processing: Enemies

17. December, 2013

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() {
    ellipse(x + tileSize/2, y + tileSize/2, tileSize, tileSize);
    textAlign(CENTER, TOP);
    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;

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) {

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() {

Let’s see what we’ve got:


You can find the final code here.

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

%d bloggers like this: