We will create a UserTank class that is derived from DrawableGameObject. We just need to implement the basic constructor which takes a Game Object. So our UserTank will get all the functions (except private ones) of the DrawableGameObject class.
public class UserTank : DrawableGameObject
public UserTank(Game g)
To begin this is actually all we need to add this tank to our game. In our game class we would add
and in our constructor we would initialize it in the same old way
hero = new UserTank();
but we do something a little different after that
Since the hero tank is a UserTank which is derived from DrawableGameObject which is Derived from GameComponent, we can put it in the GameClasses list of GameComponents. These GameComponents all get called on updates and if they are drawable, they get their draw methods called.
So now even though there is nothing "in" our UserTank class, it is being updated with our game. Lets add a couple bits of info to the UserTank class that will help us out. To save time and space, I will implement the fields of the component as public rather than making them Properties. This is lazy, don't follow my lead in this.
public Vector2 location = Vector2.zero;
public Texture2D sprite;
So we can store our location, sprite and a spritebatch to draw to. Then we simply override LoadContent, Update and Draw.
protected override void LoadContent()
spriteBatch = new SpriteBatch(this.GraphicsDevice);
sprite = this.Game.Content.Load
public override void Draw(GameTime gameTime)
spriteBatch.Draw(sprite, location, Color.White);
public override void Update(GameTime gameTime)
KeyboardState ks = Keyboard.GetState();
location.Y -= 1;
} else if (ks.IsKeyDown(Keys.Down))
location.Y += 1;
location.X -= 1;
} else if (ks.IsKeyDown(Keys.Right))
location.X += 1;
So as you see we initialize the spritebatch and load it's sprite. Then we call the base classes LoadContent method. In the Draw method we Begin our spritebatch, make a Draw call and End the SpriteBatch and then call the base classes Draw method. Then finally in the Update method we look at the KeyboardState and make some updates to the location and once again call the base classes Update method. So now that you have this component we could add it and it's logic in a very simple manner.
Here are the files for this project.