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

Writing Games with Processing: Hunting Platty

$
0
0

As it is, the game is pretty boring. The player has some control but no goal. Let’s add a routine which makes the enemies hunt the player.

There are many complex algorithms for path finding but we aim for something simple.

Add a new method to the class Enemy:

  void hunt() {
    int dx = signum(px - x) * tileSize;
    int dy = signum(py - y) * tileSize;
    
    x += dx;
    y += dy;
  }

This just moves the crocodile one step closer to where the player currently is. signum() is a simple helper function which returns the sign (1, 0, -1) of the argument:

int signum(float value) {
  return value < 0 ? -1 : value > 0 ? 1 : 0;
}

A small helper method then makes all the enemies hunt Platty in a loop:

void moveEnemies() {
  for(Enemy e: enemies) {
    e.hunt();
  }
}

Which leaves us with the last problem: When should the crocodiles move? One solution would be to move them in draw(). If you try it, you’ll see that this makes it a pretty short game – the screen is refreshed about 60 times per second but the key repeat is only 20 times per second, so poor Platty is eaten after a single step.

The solution is to move the enemies once after the player has made his move:

void movePlayer(int dx, int dy) {
  ...

  moveEnemies();
}

Et voila, hunting in 16 lines of code (click the image to start the animation):

Hunting Platty

You can find the whole source code here.

Next: Losing the game
Previous: Moving Around
First post: Getting Started


Tagged: Game, Games, Processing

Viewing all articles
Browse latest Browse all 21

Trending Articles