## Writing Games with Processing: Hunting Platty

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

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

### 2 Responses to Writing Games with Processing: Hunting Platty

1. […] Nice. We have a player character, we have control, we have enemies. What else do we need? Moving the enemies. […]

2. […] Hunting Platty First post: Getting […]

This site uses Akismet to reduce spam. Learn how your comment data is processed.