Now that we have something to shoot at, I think it is about time that we start adding in the “Tower” part of our Tower Defence. We will start off by creating a simple base class for the tower and getting it drawn, then we will move on to making it aim at our enemy. I will be leaving shooting, and placement of towers till next time. So, lets begin!
Start off by adding a new class to the project called “Tower.cs”, and make it inherit from the Sprite class :
public Tower(Texture2D texture, Vector2 position)
And that’s the basics done, go back into Game1.cs and add the following field :
All this code does is create a shiny new tower in the top left corner of our screen, using the texture we just added.
Now if you run the project you should see something like this :
Now we have our tower drawn, we can move on to something slightly more interesting, making the tower aim,
To start with we are going to give our a bigger range just for testing purposes, so go into Tower.cs and in the constructor add the following :
Before we add that we need one more field and property to store the enemy we are targeting. Add this to the top of Tower.cs :
Right, onto the aiming method, what we do here is find the direction from the tower to the target, and find out what that direction is by using some trigonometry.
For more information about finding an angle from a direction check out Riemers Tutorial.
Without for ado, here is the method :
And that’s our tower class finished for now! Go back to Game1.cs and in the Update method, just after we Update the enemy, add the following :
Here, we just check if the tower has a target, and if it doesn’t we give it one using the method we added earlier.
And that’s it for now, if you run the project you should see your black dot following the path, with our shiny new tower following his every move!
Here is the source code for this tutorial.