I implemented one of my favorite enemy types recently. I’m just so pleased with how it works I thought I’d make a dev log about it.
It’s a swarm of little wasp guys that hover around in a cloud. They begin to chase the player if he gets too close to them, and they’ll flee temporarily if he shoots and kills one of the swarm. It looks like this:
The way this works is, in addition to each wasp, there is another invisible entity representing the swarm itself. This entity contains a position, a radius, the number of wasps, and a collider that acts as the swarm’s “awareness”.
At instantiation, the swarm chooses a random starting point within its radius for each wasp. It initializes each wasp with the radius of the swarm and a reference to the swarm itself.
The wasp’s behavior is pretty simple. It selects a random point within the circle defined by the position of the swarm and the radius. It moves to that point, then selects another point, etc. If the player destroys it, it sends a message to the swarm announcing its demise and then deletes itself.
The swarm is stationary until one of two things happens: either the player enters or leaves the collider, or it receives a message from a wasp indicating it died.
If the player enters or leaves the collider, and the swarm isn’t in the process of running away, it moves toward the player’s current location at the time the event was triggered. If a wasp dies, the swarm moves toward a position away from the player’s position at the time.
Here’s a video with the colliders visible so you can see the swarm itself. The room is kind of a mess of colliders, but the swarm is the big circular one.
After moving, the swarm checks if the player is still within the collider. It either moves toward the player’s current position if he is, or stays still if he isn’t. It also sends a message to each wasp to update its destination based on the swarm’s new location.
Since each wasp moves independently of the swarm, and the swarm only tells the wasps to change destinations after finishing a move, I get an organic, haphazard movement pattern. I might need to do a little tweaking to get everything just right. But I, for one, think it is super cool.