Website/Blog about the things you need to know to make a modern RTS game
Following a path
22 Dec 2013
We’re going to make enemies that follow a predetermined path. A lot of tower defense games get by with just this as far as enemy movement is concerned.
As this series is mainly focusing on algorithms and datastructures, I’m going to skip over anything that isn’t relevant (like drawing stuff).
Setup
We’ll just keep a list of alive enemies:
And we need an enemy class, with a location and some bits for movement
We also need a path for the enemies to follow, they will start at the first point and move along the path to the last point.
The position x and y values are in grid units, with a integer (whole) number meaning the middle of that grid square.
Running it
Every game tick we need to move all of our enemies, the code for moving an enemy looks as follows.
The idea is:
Work out how far we will travel this tick.
If our target is within this distance then
Subtract the distance to it from the distance we are travelling this tick
Move us to our target point
Target the next point on the path
Finally, move us the (remaining) distance towards our target
Note: If your enemies may arrive at multiple points in a single tick, then you need to loop the inner part.
In this code, dt is the change of time variable, it contains how much time (in seconds) has passed since the last update.
It will usually be 0.0166666s (1/60) as our game is running at 60 FPS
We will also spawn enemies periodically, this is easy
Mush these together with some code to draw the enemies, grid and path and you get something like this: Running Example