Putting a Sprite onscreen
If you aren’t familiar with the term “sprite”, it refers to a two-dimensional (2D) graphical image that you can display onscreen. Sometimes they are individual images, and sometimes you can find them on what is called a SpriteSheet.
Here’s an example of a SpriteSheet:
We’ll come back to using SpriteSheets later, since that’s a little more complex than just putting a single image onscreen.
I’m going to use this image for now:
You can just right-click it and “Save As…” to your desktop or wherever, since we’ll be using it shortly.
If you haven’t already, create a new MonoGame Windows Project. (Take a look here for a refresher on the project types.)
Once you have the project created, you’ll want to add your sprite to the Content folder of your project. (right-click, Add, Existing item…)
Mine is called red_mushroom.png so you should name yours that as well if you’re following along (or, you know, change it in the code… whatever.)
You’ll need to check the properties, and make sure Build Action is set to Content and Copy to Output is set to Copy if newer, like so:
Next, open up the Game1.cs file and add the following variable under the SpriteBatch definition, before the constructor:
A Texture2D is how MonoGame (and XNA) refer to a two-dimension graphical asset.
Scroll down to the LoadContent() method and add this line:
redMushroom = Content.Load<Texture2D>("red_mushroom");
The Content.Load<> is a generic that accepts a number of different types, including audio and 3D models. You can leave off the filename extension, or add it, it won’t make a difference, and it automatically looks in the Content folder by default!
Lastly, scroll down to the bottom of the file and add this to the Draw() method, before the call to base.Draw:
spriteBatch.Draw(redMushroom, new Vector2(0, 0), Color.White);
I’m not going to go in much detail here about SpriteBatch, other than to say it provides a way to send multiple commands efficiently to your graphics card. We’ll dig into the SpriteBatch in a later post. The Draw() command has a lot of overloads, and the one we’re using takes the Texture2D, some coordinates, and a filter color. (Using white means we don’t change it at all. Try changing the color to Red or Blue and see what happens!!)
You’re done! Hit F5 and marvel in the glory of a giant red mushroom on a cornflower blue background.
I’ll cover putting some text on screen. If you came directly to this page, you can find the complete list of articles here.