Monogame References

This is a list of some quick explanations of how to do things that are covered in depth in various tutorials. This is not a replacement for a tutorial, but a place to quick review how to do something.

Collision Detection

You should keep track of locations and sizes of all game items using Rectangles. The Rectangle structure in Monogame has collision detection built in. Here is the Monogame Rectangle API:

https://docs.monogame.net/api/Microsoft.Xna.Framework.Rectangle.html

Using Intersects() to Detect Collisions.

https://docs.monogame.net/api/Microsoft.Xna.Framework.Rectangle.html#Microsoft_Xna_Framework_Rectangle_Intersects_Microsoft_Xna_Framework_Rectangle_

The Intersects() method will return True if there is any overlap between two Rectangles. If you had two Rectangle objects (ballRect and wallRect), here is how you could detect if they are in collision:

e.g. 1 - Two Rectangles Colliding

if (ballRect.Intersects(wallRect))

// Collision was detected

Using Contains() to detect Collisions

The Contains() method is overloaded with many different versions. If you have a Rectangle, you can detect whether a Point, Vector2, or another Rectangle is contained entirely within it.

eg. 2 - A Point is inside a Rectangle

mouseLocation = new Point(x, y);

if (targetRect.Contains(mouseLocation))

// code here if mouseLocation is inside the Rectangle

eg. 3 - A Vector2 is inside a Rectangle

mouseLocation = new Vector2(x, y);

if (targetRect.Contains(mouseLocation))

// code here if mouseLocation is inside the Rectangle

eg. 4 - A Rectangle is Inside a Rectangle

If (exitRect.Contains(playerRect))

// Code here if playerRect is fully inside exitRect


Load a Texture

1 - Add an image file using the MGCB Tool. Make sure that you have given the image file a short and descriptive name.

2 - Declare a Texture2D at the top of the program:

Texture2D imageTexture; // Give the Texture2D a descriptive name.

3 - In the LoadContent() method, load the image data from Content into the Texture2D.

imageTexture = Content.Load<Texture2D>("filenname"); // Do not include the file extension when naming the file.

4 - You may now draw using the Texture2D you created.

Sounds

1 - Load a sound into the project content using the MCGB Tool according to these instructions:

https://sites.google.com/gotvdsb.ca/aldworth/monogame/tutorials/sounds-in-monogame


2a - Declare a SoundEffect object at the top of the project if you are importing a small/short sound file:

SoundEffect effect;

Here is the official API for SoundEffect:

https://docs.monogame.net/api/Microsoft.Xna.Framework.Audio.SoundEffect.html

2b - Declare a Song object at the top of the project if you are importing a large/long sound file:

Song song;

Here is the official API for Song:

https://docs.monogame.net/api/Microsoft.Xna.Framework.Media.Song.html


3a - Load the sound file into the SoundEffect object in the LoadContent() method:

effect = Content.Load<SoundEffect>("soundFilename");

3b - Load the sound file into the Song object in the LoadContent() method:

song = Content.Load<Song>("soundFilename");


4a - Play the SoundEffect:

song.Play();

4a - Play the Song:

MediaPlayer.Play(song);


More Control Over Your Sound Effects

Here is a more complete tutorial on how to create a SoundEffect and SoundEffectInstance if you need more:

http://rbwhitaker.wikidot.com/playing-sound-effects

If you need more control over your sound effect than just playing such as stopping, pausing, looping, determining whether the effect is playing, etc. create a SoundEffectInstance object from your SoundEffect object:

1 - Declare a SoundEffectInstance object at the top of the project along with the SoundEffect object:

SoundEffect effect;

SoundEffectInstance effectInstance;

Here is the official API for SoundEffectInstance:

https://docs.monogame.net/api/Microsoft.Xna.Framework.Audio.SoundEffectInstance.html

2 - Use the SoundEffect object you loaded in the LoadContent() method to initialize the SoundEffectInstance object:

effect = Content.Load<SoundEffect>("soundFilename"); // Do not include the file extension when naming the file.

effectInstance = effect.CreateInstance();

Play, Pause and Stop

effectInstance.Play();

effectInstance.Pause();

effectInstance.Stop();

Loop

After you have created the SoundEffectInstance, set it to loop before you play it:

effectInstance.IsLooped = true;

effectInstance.Play();

Check the Status of the SoundEffectInstance

if(soundEffectInstance.State == SoundState.Stopped)

{

// ...

}

Other possible SoundStates are Playing, and Paused.

Draw Text

1 - Create a SpriteFond Description using the MGCB Tool: http://rbwhitaker.wikidot.com/monogame-drawing-text-with-spritefonts

2 - Declare a SpriteFont object at the top of your program:

SpriteFont titleFont;

3 - Load the SpriteFont from Content in the LoadContent() method:

titleFont = Content.Load<SpriteFont>("TitleFont");

4 - Print some text to the string in the Draw() method:

_spriteBatch.DrawString(titleFont, "You Rule!", new Vector2(10, 10), Color.White);

Keep Track of Time

Time Since Program Started

1 - At the top of the class, create a variable to track elapsed time.

float seconds;

2 - Update this variable in the Update() method:

seconds = (float)gameTime.TotalGameTime.TotalSeconds;

The variable seconds will now tell us how many seconds have elapsed since the program began.

Track Time Starting at Any Time

You may want to keep track of how much time has elapsed since a particular event occurs in your program. See the image below for a visual of how this works.

1 - Create a variable that takes a time-stamp of when you want to start timing. Declare it along with your seconds variable:

float seconds;

float startTimer; // We will update this only when we want to start tracking time

2 - Update your timeStamp variable when you want to start tracking time:

startTimer = (float)gameTime.TotalGameTime.TotalSeconds;

3 - By subtracting startTimer from the total elapsed time, we can determine how much time has passed since we last updated startTimer:

seconds = (float)gameTime.TotalGameTime.TotalSeconds - startTimer;

Change the Window Size

The following code allows you to specify the window width and height:

_graphics.PreferredBackBufferWidth = 800; // Sets the width of the window to 800 pixels

_graphics.PreferredBackBufferHeight = 500; // Sets the height of the window to 500 pixels

_graphics.ApplyChanges(); // Applies the new dimensions

Put this in the Initialize() method to have your window be this size when your program first starts, or put it elsewhere to change the window size at a different time.

Change the Window Text

The following code allows you to change the title text in your game window:

this.Window.Title = "This text will be the title!";

Put this in the Initialize() method to have your window start with this title, or put it elsewhere to change the window title at a different time.

Change Opacity of an Image

You can change the opacity level of a texture when you draw it easily by altering the Color Mask. Here is an example of a normal method drawing a Texture2D:

_spriteBatch.Draw(imageTexture, locationRect, Color.White);

In order to make this texture partially transparent change the draw method to the following:

_spriteBatch.Draw(imageTexture, locationRect, new Color(Color.White, 0.5f));

We have set the opacity of the above texture to 50%. You can set the opacity to any percentage by specifying a number between 0 and 1.

Drawing Images

All images, fonts etc. that are drawn, must be done in the Draw() method. They must be between the Begin() and End() method calls:

_spriteBatch.Begin();

// All drawing code goes here

_spriteBatch.End();

Draw an Image

First, the image you wish to draw must be stored in an instance of the Texture2D class, and loaded from Content.

There are 7 Draw() methods. We used 2 formally in class, but you may need some of the others for more advanced programs.

Keyboard Events

Here is a good tutorial: http://rbwhitaker.wikidot.com/monogame-basic-keyboard-input

In order to detect events from the keyboard, you must declare a KeyboardState object:

KeyboardState keyboardState;

At the beginning of the Update() method, you must update keyboardState:

keyboardState = Keyboard.GetState();

You can set your program to listen for specific keys using an if statement in the Update() method. You can get the state of any key through the keyboardState object and determine if it is pressed or not pressed:

Check for a pressed key:

if (keyboardState.IsKeyDown(Keys.Space)) // Use intellisense to help you listen for any key

{

// Code to happen if the space bar is pressed

}

Check for a released key:

if (keyboardState.IsKeyUp(Keys.Right)) // Use intellisense to help you listen for any key

{

// Code to happen if the up arrow is not pressed

}

The code in the above if statements will be run each time Update() is called while the specified key is pressed or not. You may only wish something to happen once per keypress. To do that, declare two keyboardState objects:

KeyboardState keyboardState;

KeyboardState previousKeyboardState;

At the beginning of the Update() method, store the previous keyboard state, and then update the current one:

previousKeyboardState = keyboardState; // We can now see if the state has changed.

keyboardState = Keyboard.GetState();

We can now use an if statement to determine of a key is currently pressed, but was previously not pressed:

if (previousKeyboardState.IsKeyUp(Keys.Left) && keyboardState.IsKeyDown(Keys.Left))

{

// This code will be run only when the left arrow is first pressed

}


Mouse Events

Here is a good tutorial: http://rbwhitaker.wikidot.com/monogame-mouse-input

In order to detect events from the mouse, you must declare a MouseState object:

MouseState mouseState;

At the beginning of the Update() method, you must update mouseState:

mouseState = Mouse.GetState();

You can set your program to listen for specific keys using an if statement in the Update() method. You can check the state of the various mouse buttons through the mouseState object and determine if it is pressed or not pressed:

Check for a pressed key:

if (mouseState.LeftButton == ButtonState.Pressed)

{

// This code will be run when the left mouse button is down.

}

Check for a released key:

if (mouseState.RightButton == ButtonState.Released)

{

// This code will be run when the right mouse button is up.

}

The code in the above if statements will be run each time Update() is called while the specified key is pressed or not. You may only wish something to happen once per mouse click. To do that, declare two mouseState objects:

MouseState mouseState;

MouseState previousMouseState;

At the beginning of the Update() method, store the previous mouse state, and then update the current one:

previousMouseState = mouseState;

mouseState = Mouse.GetState();

We can now use an if statement to determine of a mouse button is currently pressed, but was previously not pressed:

if (mouseState.LeftButton != prevMouseState.LeftButton && mouseState.LeftButton == ButtonState.Pressed)

{

// This code will be run only when the left mouse button is first pressed

}


Changing Background Color/Image

Background Color

In the Draw() method, simply change the color int he call of GraphicsDevice.Clear() call:

GraphicsDevice.Clear(Color.CornflowerBlue); // Specify any color you wish here

Background Image

To change/add a background image, you ust add it using the content builder. Make sure that its size/quality are large enough so that when you scale it to the size of your window it still looks good.

In the Draw() method, just draw the background image to a Rectangle located at 0, 0 that has a size that is equal to the size of your game window:

_spriteBatch.Draw(backgroundTexture, new Rectangle(0, 0, _graphics.PreferredBackBufferWidth, _graphics.PreferredBackBufferHeight), Color.White);