Tower Defense

First tower defense game 😀 Of course, it doesn’t have all the bells and whistles of commercial games. But it’s simple enough to play a couple of times.

If this project taught me anything, it’s that some things are easier with Vectors. The key to any good tower defense game is predicting the path of the enemy in order to hit!

Diagrammatic representation

Simply aiming at the enemy when you’re about to fire is no good. He isn’t likely to hang around there for two long!
The problem and its givens are listed:

We know,

  • The position of the enemy(which moves) at the time of firing
  • The position of the gun (which doesn’t move)
  • The absolute velocity (speed) of the bullet. (The direction is what we need to determine).
  • The direction and magnitude of the velocity of the enemy

My approach was as follows:

In order to hit the enemy, the final position of the bullet and the enemy must be the same. Also, in time t, the displacement of the bullet and the enemy must be equal. This is written vectorially as:

Which on expanding,


And on squaring and rearranging,

Where cos θ is given by,

Solving this equation using the quadratic formula, and selecting the positive root (since time can’t be negative, in this discussion), will give us the time after which the bullet and the enemy will collide.

Velocity of the bullet is then given by:

Keep in mind that they’re all vectors, so you need to write appropriate classes/structures to deal with them.

Game Screenshot

Source

Executable (Windows) 

Advertisements
Next Post
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: