Now that we have the ability to place down tower’s and have a basic targeting system working, we can move onto making our tower’s shoot so we can finally obliterate that little black dot smugly walking along our path!
We are going to start off by creating our first type of tower, the “Arrow Tower”, then move on to creating a “Bullet” class, and to top it all off, we will combine the two classes and create a targeting shooting tower.
Right, let’s begin! Before we create our new type of tower, there are a couple of changes we need to make to “Tower.cs”. Add the following field to the Tower class :
Then modify the constructor so it looks like this :
I’m sure you are asking, how will this kill a bullet? Well, if you look up at the last bit of code we added in the “IsDead” property, you will see that if a bullet is older than 100, it is classed as dead, so by setting a bullet’s age to 200, we are essentially killing it.
One of the final things we are going to add is an update method for the bullet, without this, the bullets would just sit in the barrel of the tower doing nothing :
In the real world, when we shoot a bullet out of a gun, it is pretty much going to move linearly (in a straight line) until it hits something, but we aren't making a simulation! It would be frustration for the player if his towers never hit any enemies because they moved to fast and the bullets just zoomed behind the enemies! So we are going to cheat, we are going to “bend” our bullets, as if we were in the film “Wanted”. To do this, every frame we are going to making sure our bullet is moving towards our target :
For more information on this see Riemers Tutorial.
This line just updates the timer, this will be set to zero when a bullet is fired.
IsInRange is a very simple method that just checks whether or not a point is within the range of the tower. Last but not least we will add in the method that will draw our bullets :
Lastly find the following line in the Update method :
And replace it with this :
All that is left now is to go into Game1.cs and find the code where we create a new Player, and replace it with this :
Then all we must do is add the following image to the Content Project :