[2021 Update!] Make Games with MonoGame - Installation and Development Fundamentals

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello my name is kyle and in this video i'll show you how to install and set up the popular game framework monogame as well as go over the core fundamentals of developing games with it first we'll get visual studio installed and then grab the latest version of monogame all of this is free by the way i'll then show you how to create new projects how the code is organized and how to manage your game assets using the pipeline tool and finally most of this video is dedicated to creating and coding our own original game which will utilize several key aspects of game development like drawing graphics to the screen displaying text keeping score storing data and variables and reading mouse input from the player with all that said let's get started let's go ahead and get everything installed that needs to be installed for us to work with monogame to start i'm at monogame.net once you get to the site i would recommend going to this download section and find the latest release for me it is model game 3.8 so let's choose this and what's nice about this is that typically they post lots of different helpful links and tools that make getting started a lot easier in this case we have this getting started guide in this video we're simply going to go through the steps that are outlined here you can choose whichever operating system worked for you for me i'm on windows so that's what we're going to be working with today to start we do need to install visual studio which you can find over here at visualstudio.microsoft.com there should be an option to find visual studio specifically and there is a free version of this ide which you can find community so whatever the latest version of community is go ahead and download that just a word of warning visual studio is a very large program and downloading it and installing it will take quite a while but as you go through the installation steps you will come across a screen that looks similar to this this is where we choose specific workloads or different packages and features to be included with visual studio we will need net core cross-platform development once you finally get visual studio installed i know it takes a while but once it's done go ahead and start it up and you should be greeted with a screen that looks something similar to this our next step if we go back to our documentation is to install the monogame extension for visual studio and that process is pretty simple first we need to actually enter visual studio which you can do with this link right here continue without code and that will open up visual studio itself from here we want to go up to this extensions option and manage extensions now in here we can find all kinds of different extensions that are offered for visual studio but the one that we're most interested in is if we go up to the search bar and search for monogame you will find one called monogame project templates and it's already installed for me but for you there should be a little download button that you can click once you click download on this template it'll give you a little message that says you'll need to close down visual studio in order for the process to begin so go ahead and do that once you close out you should have a little pop-up window that comes up and go ahead and click the modify button once it's done and it will go ahead and install the extension for visual studio finally just a couple more steps if we go back to the docs here and we scroll down just a bit more we will find that we need to install the mgcb editor this editor is used to manage our content which is very important and installing this is actually very easy we have two commands here and we simply need to run them with the command prompt so i'm going to copy this first line copy and then we need to open us a command line so you can go to your start menu type cmd for command prompt then once you're here you can right click to paste in this command and then you're just going to click enter and when you click enter it will install the mdcb editor for me it's already installed so it won't work but for you it will install it then we need to go back copy this then back in the command prompt once again copy this command in press enter and we are good our mdcb editor is registered and we're done except there is one other optional step to install some additional model game templates which you can go ahead and do i'll copy this back in command line i will paste this in and enter to install these templates once you have that done everything is installed and you are ready to go now that everything's installed we're going to go through the process of creating a simple game i'll show you how to create a new mono game project through visual studio how to import all necessary assets and how the code is laid out here's a quick demo of what we'll end up making it's a simple shooting gallery game you can shoot the target with your mouse your score increases and the target jumps to a new spot concepts like displaying graphics changing variables and reading player input is necessary for any game and this small project goes through this process very nicely as a side note mono game utilizes c-sharp for all programming if you don't have any coding experience or you aren't familiar with c-sharp i do have a full monogame course on udemy that has several sections that teach c-sharp programming which assume no prior technical knowledge there's a link in the description feel free to check it out up next we'll create our monogame project and go over its structure we're going to get things started by opening up visual studio and we're going to go ahead and create a new project now the first thing we need to do is select a template if you go up to the search and search for monogame we can certainly find the correct template which is this one monogame cross platform desktop application opengl this is the one we're looking for if you select this and choose next then the project name you can name this whatever you want i'm going to name it shooting gallery to match the game that we're making make sure you keep track of what location you save this project in and i prefer to have this box checked for place solution and project in the same directory and when it looks like it's finished go ahead and double click on this game1.cs over here this file will act as kind of a home base for our game a lot of the core mechanics of our game come from here and actually for our first game we're going to put everything in this file it's good practice to separate your code into different files but while we're learning with this smaller scale game i think it's best if we keep it simple and all in one place before doing anything else i like to start the project right away which you can do with this start button at the very top the first time you run it might take a bit longer but every time after that it should be quick and if you see a small colorful window pop up that means it's working now depending on your version of monogame your game1.cs might look a little bit different from mine but that's completely fine it should still have a very similar structure to this where you have a game one class as well as some similar methods to what you see on screen here if you scroll down you'll see that we have several different sections we have initialize load content update and draw each of these different sections performs a different action for our game and what we as the programmer have to do is write our code for each of these sections that's what this to do section this to do comment is talking about all we're going to do is add our own code to these methods let's go through each of these sections one by one to get a better understanding of what they do we'll start off at the very top with this game1 method this is known as the constructor but what you need to know about this section is that it's in here where we set up some basic settings for our game like we can set the window size here or we can change whether or not the mouse is visible in the game window simple features like that this next section initialize this section of code occurs right when the game starts and you use it to load certain components into your game and apply certain settings now next we have load content which this method is definitely one that we'll always be using here is where you can load all of your images sounds and other pieces of content into your game our shooting gallery game is going to have several images that we're going to use so we'll be using this method here a little bit in the coming lectures next up is the update method here is where all the interesting stuff for our game happens this is our game loop this section of code runs every frame of our game in monogame the projects we make will by default run at 60 frames per second so that means that this section of code right here is going to run 60 times every single second knowing this we can put code in here that needs to be constantly updated which you'll see very soon how this works and lastly we have our draw section in here we're going to put in anything that involves drawing stuff to the screen if we wanted to show a target in the game window we would put our code to do that in here now this section is very similar to the update section in that it also runs once every frame however this method is used solely for drawing images and text you wouldn't want to perform any calculations or change any variables in here you would do that instead in update and that takes care of each of the sections at the very top we have our constructor which handles basic settings for the game initialize loads in certain services that we'll discuss later on load content lets us include our art assets into the code update is our constant game loop and draw displays graphics and fonts to the screen in the next lecture we're going to go over how to load assets into your game and in the following lecture we'll talk about how to display those assets to the screen in the game window let's get started with actually building our game the first thing we're going to work on is getting our art assets included into our project there are three images that we'll be using for this game one for the crosshairs one for the sky background and one for the target itself there's also a font file that we'll be using check the description for a link where you can download a zip file containing each of these assets once you download the zip you can just extract the zip file and you should see all of these images now in order to get all of these available for our game we need to utilize monogames content pipeline all of those assets need to be converted into a new kind of file type in order for them to work with monogame and that's exactly what the pipeline can do for us over here on the side you should notice that there is a content folder if you expand that you should find a content.mgcb file right click on it choose open with and then in this list of options over here you want to scroll down and find this mgcb editor if you click on this and then you can click on this set as default button then choose ok it'll eventually after a little bit of time open up a window it might take longer for you if it's the first time you're ever opening up this window but this is our mgcb editor or the content pipeline it's here that we'll find the images on our computer and bring them into our project to do that we need to click on this add existing item button and then we're going to need to navigate to wherever you saved those files to your computer for instance i have mine just in my downloads folder if you find the extracted folder you should find all four of the assets so if you select all four of these and then choose open and then i would recommend copy the file to the directory which will add a new version of those files to your monogame project so make sure you have this one selected and then i recommend clicking on this box for use the same action for all selected files which will mean that it will do this copy file to directory for each of the assets and then just click add and once you do that you should find that all four of the files were added underneath content which is exactly what we're looking for at this point we can go ahead and save this file and then we're going to want to build what you can do with this button right here either build or rebuild and once you do that and it says build successful then you can go ahead and close out of this window that's everything that we need to do with the content pipeline for now once you do that you'll notice that your content file over here on the side is a little bit different from before and now has a bin in an odd folder and in particular in the bin folder if you expand that and expand this desktop gl you'll find that we have four new files in here one for each of the assets except now each of these assets has a dot x and b file type these are the monogame specific assets that we'll be using for the project in the next lecture we'll learn how to take these and actually display them in our game we have three images and one sprite font file in our content folder now let's go over how to actually get these to display on the screen we'll start with the images the first thing we need to do is make a variable for each of the images and we'll declare them here at the top we'll type in texture 2d target sprite so here the data type is texture2d and the name of our variable is target sprite texture2d is basically a two-dimensional image or as game developers call them sprites i'll be referring to these image assets as sprites from now on you may notice that we didn't give this variable a value what we're going to do is declare the variable here and then give it its assigned value later on in the program and while we're here let's go ahead and add variables for the other images as well texture 2d cross hairs sprite and also texture 2d background sprite now we're going to go down to the load content method and we're going to do the assignment for those variables remember the load content method is to load our art assets into the game so that explains why we don't do the assignment up at the top in here we're going to write in a line that says target sprite equals content dot load and then use these two symbols here and inside we will write texture 2d and then after this we need two parentheses inside the parentheses we're going to use quotation marks and say target with a semicolon at the end let's go through this line bit by bit target sprite is the same variable that we declared up at the top and we're setting it equal to content.load which is a monogame function that lets us load our assets from the content folder and this next part right here is a little bit different we use these symbols and in between the symbols we need to specify what kind of asset it is and here we specify texture2d and you'll notice that texture2d is the same type that we defined right here for our sprite variables whenever we load content we always are consistent with this and then finally we have the parentheses just like any other method and inside the parentheses we have a string that says target if we take another look at our content folder you'll see that we have all of our different assets and they're called dot x and b files when i say string target in the parentheses here i'm referring to this target.x and b i'm just not saying the dot x and b part monogame knows that when i say string target it's referring to this file right here so that explains how we loaded in our xmb file to the target sprite variable now let's do the exact same thing for the other two sprites i'm going to copy this line and just paste it again this time let's do cross hair sprite and the string name for this asset is called cross hairs and then one more sprite this is going to be background sprite and this sprite over here is called sky dot x and b so in the string here we'll say sky now that all of our sprites are loaded into our game let's go ahead and draw them we're going to do this down in the draw section but before we do that let's go ahead and save and run the game as is just to make sure everything is good to go it's always a good idea to run your game periodically to make sure that there's no errors or anything going wrong if you wrote a line incorrectly the program won't start up and you'll have to press the square stop button in order to stop the program and fix the issue luckily whenever that happens the messages are very helpful and will often tell you exactly where your mistake was and what went wrong but ours seems to be running just fine it should just be a blank colorful game window so we're ready to make it more interesting by drawing some images to it now before we draw the sprites though we need to understand what a sprite batch is a sprite batch is a tool that monogame provides for us and that is what does the actual drawing to the screen if we go back up to the top of the file you'll see that the template that we loaded in actually auto-generated a sprite batch for us it declares it at the very top of the file and down in load content it gets initialized right here this object is what we'll be using to do our drawing and this is how we do it down in our draw section we can get rid of this line and here we're going to write in underscore sprite batch which is the name of our sprite batch dot begin with two parentheses and a semicolon this line alerts the sprite batch and tells it hey we're about to draw something to the screen next we're going to do a underscore spritebatch.draw with two parentheses and a semicolon now inside these parentheses we have to specify a few things in order for it to draw exactly what we want but for now just go ahead and copy what i'm putting in and in the next lecture we'll do a deeper dive into what everything here means first is the sprite we want to draw which is target sprite next is the position as a vector which is new vector 2 0 0. and then finally we have the color color dot white and then after we're done drawing we need to make sure that we call underscore sprite batch dot end in order to tell the sprite batch that we are done drawing so to recap how this worked we call spritebatch.begin to tell the sprite batch that we're ready to begin drawing then we call spritebatch.draw to actually draw the sprite or sprites that we want to draw and then finally we call sprite batch dot end now in between begin and end we can have multiple different draws but here we're just drawing one sprite so we only have one call to spritebatch.draw with all this in place let's go ahead and save and run and there it is in the upper left-hand corner of our game window we see our target sprite so our sprite batch successfully worked and i know that was a lot of work to get to this point and a lot of information to take in but in the next lecture we're going to take a step back and really examine the sprite batch.draw method and understand what made it draw the target to the upper left hand corner of the screen here i want to talk more in detail about how this spritebatch.draw was able to draw the target to the screen it takes in three parameters first the texture2d that we want to draw or the sprite next is a vector2 and then finally a color now this vector 2 we haven't even talked about what a vector 2 even is in this context it's being used to describe the position of the image that we're drawing i'm going to run the game real quick just to better explain this in 2d game development the game world is like a big grid it has an x-axis that goes left and right and it has a y-axis that goes up and down this is very similar to high school math classes where you have to plot ordered pairs on a graph that's exactly what this vector 2 down here is it's an ordered pair this first value is how far left and right on the grid you want to go or the x position and the second value is how far up and down you want to go or the y position of course at the moment we chose the position 0 0 also known as the origin which in monogame the origin is the upper left hand corner of the game window so what would happen if we change this first value from zero to let's say 150. if we save and try this we'll find that the target has moved to the right a little bit more specifically it moved to the right 150 pixels because 150 was defined for the x position now what would happen if we change the y position to 150 as well if we save and run now we will see that the target has moved down from before specifically it has moved down 150 pixels and since we left the 150 for the x position still there 150 150 means right 150 pixels and down 150 pixels now it going down this may be different from what you remember from like algebra class in those textbooks if you wanted to plot a point that was higher up on the graph you would want to give the y value a higher number in monogame though and a lot of other game frameworks as well the y-axis increases downwards that means that the higher your y-value is in the ordered pair down here the more down on the screen your sprite will be drawn if we change this 150 to say 300 now and we save and run we will see that is even farther down the screen than before it's 300 pixels down so this kind of explains how the grid system works in monogame and that's how we utilize this new vector 2 right here we will be utilizing vector 2s quite a bit in the coming games since that is the best way to define the position of an object in our game now finally this last parameter is color.white it's just defining some color for our sprite so when we say color.white here that means that we are going to draw our sprite with a white tint to it except when you put a white tint to an image that doesn't really change anything let's try this instead instead of color.white let's try color.green now if we save and run you'll notice that the sprite is now tinted green it's a lot different from before so this is why we choose color.white when we don't want to change what the color of our sprite looks like when you do white nothing changes for the sprite now that we have a better idea of how drawing works in general let's go ahead and draw the background we can actually copy and paste this line right here for the target copy and paste but this time we're going to change the target sprite to drawing the background sprite and let's also change the position from that to zero zero so once you have that in place let's save and let's run and see what we got we now get a nice cloudy sky background but you'll notice that the target is just suddenly not there anymore and this has to do with our draw order you'll notice that we put the background sprite after the target sprite but if i were to let's say cut this line out and instead of putting it before the background let's put it after so now we're drawing the background sprite and then we're drawing the target sprite if we save and run now our target has come back and this simply has to do with our drawing order see when you draw sprites to the screen the order that you draw them in is very important what was happening before is that the background was being drawn on top of the target so the target was still being drawn but the background was covering it up drawing sprites to the screen is kind of like painting a picture if you painted a picture of a cat and then you painted a picture of a house on the same canvas you wouldn't see the cat anymore because the house was covering it up and technically the cat is still there but it's covered up and you can't see it this is just something to keep in mind as we go through our games let's wrap up this lecture by actually getting rid of our target sprite draw we'll bring it back soon but we're going to work on a few other things first i hope you didn't forget but there is one more asset that we need to load into our game and that's gallery font dot sprite font in order to draw text to the game window you have to utilize a type of file known as a sprite font these files are basically just blueprints for monogame to follow in order to understand how the text will be drawn like what size the text will be and which font to use i want you to go find the galleryfont.spritefont file that you downloaded not the xmb but the one that you downloaded you should be able to see it over here actually in your content folder down below your content.mgc the galleryfont.spritefont file should be right here and if you click on it once it should open up to show you what its contents are in reality it's basically just an xml file but it's centered around fonts and monogame knows how to read these you'll see all sorts of options for customization like the font name or the size and the spacing things like that all you have to do is make adjustments and change each of these properties to fit whatever context you want this font to be used in for example i could change this 24 to say 32 and then when i recompile in the content pipeline it should update to the new size as it is this is a pretty basic sprite font that we're using for this game but it definitely gets the job done if you ever want to make your own sprite font i'd recommend just making a duplicate of this one and then adjusting the properties to match what you need now going back to our code if you change back to the tab for game1.cs let's go ahead and get started with importing this into our game this process is very similar to what we did before with the sprites so up at the top we're going to add a new variable for sprite font and i'll call this game font with a semicolon and actually i'm going to get rid of this gap then down in the load content section we can do the same as before where we just say game font the name of our font equals content dot load and then we need to specify the type that this is which this time it's a sprite font and then in parentheses we're going to put in the string for our sprite font which is called gallery font gallery font now for the line that actually draws the text this goes down in our draw section and same as before we need to utilize the sprite batch to do this and also same as before sprite batch begin and sprite batch dot end has to occur before and after the draw but conveniently we can just use this same sprite batch begin in sprite batch.end from before so we're killing two birds with one stone here so here is what the code for the text draw looks like spritebatch.drawstring and then the first parameter is the font we need to use which is just game font whatever we named that next is the message that we want to display so i'm just going to display test message next we need to define the position which is a new vector 2 and we'll put this at position 100 100 and then lastly we need the color i'm going to choose color dot white so i know that this is a pretty long line so take a quick look at what we're doing here oh and don't forget your semicolon but we have four parameters the font the message the position and the color all of which is going inside of spritebatch.drawstring and overall you'll notice that this is a very similar format to how we did spritebatch.draw with the images but there is an extra parameter for the font that we'll be using so go ahead and save and run and there's our message although it was kind of a pain getting that sprite font loaded into the game now that it's there printing out text to the screen will be very easy so a couple of lectures ago we drew the target sprite to the screen at a specific position the thing is the target is going to be changing positions every time it gets shot so we can't just hard code the target to appear at position 0 0 or something instead we need to make the target's position be a variable that way whenever the target gets shot we can update its position variable to be somewhere else on the screen and therefore the sprite will follow suit to do this let's go to the top where all of the variables are at and after these sprites and sprite fonts let's go ahead and create a new vector2 target position and i'm making it a vector 2 to match what is required for the sprite batch.draw same as before now let's go ahead and give it a new value too we're going to say target position equals new vector 2 and let's give it a position of 300 300 with a semicolon at the end so this format might look a little bit strange to you in particular we're writing this word new in there we didn't do that with the other variables so why are we doing that here well the reason for this is because vector 2 isn't really a data type it's actually what's known as a class classes are similar to data types but they operate a little bit differently a lot of these other data types for the variables such as sprite font and texture 2d are also classes as well and aren't really data types so for now just pretend like it's a standard data type and we'll just keep moving forward from here so now that the target position is a variable let's use it to draw the target sprite so back down in draw we're going to add a new sprite batch dot draw and this process is going to be the same as before when we drew the target sprite so we just need to specify the texture 2d which is target sprite next we need to define the position which we just made with target position and then finally the color which will make be color dot white this time we're not using a new vector 2 we're using our target position variable when we do the background sprite we had to create a new vector 2 and put it in for this parameter but we already did that up at the top with target position so we don't have to do that here we need to say target position having this setup like this whenever we want to update the target's position in the game all we have to do is update this variable right here and when this variable gets updated the draw method is going to notice that and the target sprite is going to correspond to whatever target position holds so go ahead and save and run the game now just to verify that this works and there it is our target sprite is being drawn at position 300 300 just like we specified at the very top of the file so we have the target's position saved as a variable and that'll be very helpful to change its position whenever we want there is one more aspect of the target that we should have stored in a variable and that's its radius since the target is a circle its radius is the distance from the center to its edge having this value on hand will be helpful in the coming lectures because we'll be performing some calculations based on the target's size so i figured now would be a good time for us to get this variable set go back up to the top where the variables all were created and let's make a new one for the target radius i'll call this int target radius and i'll start this off at a value of 45. i got the number 45 because if you look at the target image its width is 90 pixels therefore the radius is 45 which is just 90 divided by 2. now we could leave this like this and that would be perfectly fine but this variable is a bit special see throughout the course of the game this variable isn't going to change the target is always going to be the same size so the radius is always going to be 45 it's never going to change away from that so when we have a variable in our program that will never change it's good practice to make it a constant variable when a variable is constant that means its value can't be changed anywhere in your code and anyone reading your code will know that it isn't going to change we can make this variable constant by simply putting the keyword const right in front of where we created our variable with just this change this variable's value will now never change from 45 and it can't if we tried to change target radius anywhere in our code it just wouldn't work and that should do it having this variable available for us to use will prove to be very useful in the coming lectures in addition to that if we ever change the sprite for the target to something else and the size is different all we have to do is change this one variable and nothing else in our code will have to change in this lecture we're going to go through how to get input from the mouse or in other words have the player be able to click on the screen in order to make something happen since this game is a shooting gallery sort of game it works by having the player click on the targets to shoot them so let's walk through how to make this happen first we need to talk about how the mouse communicates with the game monogame is able to tell what the mouse is doing and where it's at at all times and we as the programmer are able to access the mouse's current state when i say state i mean what exactly the mouse is doing at that particular moment this includes where on the screen the mouse is located if the left or right button is pressed down if the scroll wheel is being used and other cases as well by looking at the mouse's state we're able to determine what our game should do now in order to access the mouse's state information we need to create a variable for it so up with the rest of these variables let's go ahead and create a new one i'm going to call this mouse state m state so same as always mouse state is our data type or the class type i should say and m state is the name of our variable now in order to give it the value that we want which is the current state of the mouse we're actually going to do this assignment down in the update method this will be our first exposure to working in the update section of the game so just as a reminder all the code that's written in here gets executed every single frame of the game now with that in mind it makes sense to put this assignment in here we'll say m state equals mouse dot get state with two parenthesis and a semicolon so this line uses mouse dot get state which is a method that as expected returns the current state of the mouse and since m state is being set equal to this that means that m state will contain the current mouse state and this is the reason that we put this in the update method every single frame this line is going to get updated therefore every frame our m state is going to be up to date about what the mouse is doing and where it's at now that we have this information easily accessible let's actually do something with it let's start with something easy how about we make a variable and whenever the player clicks the mouse that variable increases so let's create a new variable at the top i'll call this in score equals zero so just an integer value starting off at zero and then like i said every time the player clicks we want that variable to increase so that means that after this line we're going to test to see if the mouse's left button is pressed down and if it is that must mean that the player clicked we're going to utilize an if statement to do this so we're going to write if m state dot left button is equal to button state dot pressed and then don't forget your curly braces for the if statement so here's what this line is saying end state is just this variable right here it contains the mouse's current state and then by saying dot left button we're accessing the current state of the left mouse button of the mouse then by using the double equals sign that means we're currently testing to see if the left mouse button is equal to the pressed state or if it's pressed down so to sum this up this line asks if the mouse's left button is pressed down then do the code inside of the brackets and what we want to do when the mouse is pressed down is just increase the score which we can do with score plus plus and as a reminder the plus plus notation just means increase the value of this variable by 1. let's go ahead and save real quick and test this out and see what happens so we programmed it to make it so whenever we click the score will increase we're clicking but nothing's happening maybe behind the scenes it is but we have no way to tell what the value of the score is let's make it so that the score is displayed to the screen to do this we're actually going to recycle this drawstring method that we programmed earlier right now it's just displaying test message but that doesn't really accomplish anything it would be more meaningful if in here we displayed the score value so to do that we can just type score but you'll notice that if you just type score in there it will give us an error and this is because it says it cannot convert from int to string see score is an integer and this parameter in here for drawstring expects a string value now all's not lost we can actually convert an integer to a string very easily all we have to do is say score dot 2 string with two parentheses at the end just like that what tostring does is it takes the value on the left score and simply converts it to a string so now this should work more appropriately go ahead and save and let's run once more and there's our score value right there it's just 0 right now and whenever i click it goes up but you'll probably notice that it's not really behaving as you might have expected whenever i hold down the mouse button it continuously increases and this is because the code that we put for this is located inside of the update method every single frame is testing to see is the left mouse button pressed down and if it is it's going to increase the score leaving it like this would be fine but i think it would be better if we only increased the score once right when the player clicked we're going to be applying this code to shooting a target and we only want that shot to occur right when the player clicks not every single frame that the button is pressed down so here's how we're going to get around this we're going to create a new variable that keeps track of whether or not the mouse button has been released or not so in addition to m state i'm also going to make a bool or boolean called m released i'm going to start this off at true again bool or boolean just means true or false and using that value back down in update we're going to update this if statement a little bit we only want this score to increase if the mouse has been released on the previous frame so to check this we can add to this if statement with and m released is equal to true so how this works is this if statement is now checking two different conditions in the same if statement it's checking is the left mouse button pressed down and is the m released variable equal to true only when both of those conditions are met is it going to do the code inside of the brackets so now that the if statement tests for both of these variables we need to make it so that the score increase only happens once every time that the player clicks so inside here if we were to add a line that says m released equals false that means as soon as the score increases m release is going to change to false so the next time update method runs m release is not going to be true anymore it's going to be false meaning that the score will not keep increasing so let's save and run now and see what happens the score starts off at zero and if i click the mouse it goes up by one exactly what we want however if you keep clicking nothing happens and this is because the m released variable this one never goes back to true therefore this portion of the if statement is never fulfilled and the score can never increase again to fix this we just need to add another section that will change and released back to true and we can do this right here we just need another if statement we'll say if m state dot left button is equal to button state dot released this time so every frame of the update we're going to check to see if the left mouse button was released and if it ever gets released then we'll just change the m release variable back to true very simple so just to kind of review how all of this works m release starts off at true whenever i click the left mouse button it's going to see that the left mouse button is pressed and m release is true therefore this code is going to run our score is going to increase and m release is set to false meaning that the next frame this section of code will not run again because m release is false however at any point when the player releases the left mouse button this if statement is going to get triggered meaning that the left mouse button is released so m release goes back to true which means that the next time that the player clicks the left mouse button this if statement will be fulfilled and the score will increase again it's a nice cycle so now if we save and run the moment we click it goes up and i'm holding the mouse button down it's not increasing anymore and i can keep clicking every time i click it goes up by one it's exactly what we want so now that this is in place in the next lecture we're going to apply this new code so that we can now shoot the target specifically as of now we can click anywhere on the screen and our score increases let's make it so that this only happens when we click on the target itself so here's the mental challenge with this when we click the mouse how can we tell if the mouse is on top of the target sure it's easy for us as humans to tell because we can just look and see but how can we make it so our program can tell here's a hint we need to utilize the position of both the target and the position of the mouse we have the x and y coordinates of both using that information how can we know that the mouse is over top of the target it's little questions like these that make programming so much fun you just have to sit back for a moment and think about the data that you have available and how you can use that data to get the answers that you want here's what i'm thinking if the mouse is close enough to the center of the target then it's a hit but obviously if it's too far away then it won't be a hit specifically if the distance between the mouse and the target is less than the size of the radius of the target then the mouse must be over top of the target for example if the mouse was here the distance between the center of the target and the mouse is larger than just the radius of the target so that means that the mouse is outside of the target but if the mouse was here instead the distance between the points is less than the radius so it's inside it's pretty simple logic let's go into the update method to implement this for this if statement that tests for mouse clicks we can actually put an if statement inside of here to test the distance between the mouse and the target it is perfectly fine to have an if statement inside of another if statement this is called a nested if statement and they'll come up once in a while so here let's actually get rid of the score increase for now we'll add it back later and to start we'll get our if going we just say if then parentheses and then we have our curly braces and then now for the contents of the if statement we need to see if the distance between the mouse and the target is less than the radius of the target we might have to do that calculation elsewhere and come back to this if statement in just a second let's instead make a new variable that stores this distance and we'll do the calculation in this update function here we'll call this float mouse target dist notice that i made this variable a float or a decimal number rather than an integer this calculation will most likely not return a solid integer and we need to account for that here in this new variable we need to get the distance somehow luckily for us this is pretty easy with monogame there's a function that's provided for us called vector2 dot distance and then all we have to do is put in two vector twos into the parentheses here and it will calculate the distance between those two vector twos or in other words the distance between those two points again those points are the targets position and the mouse's position so first we'll start with the target's position that's just target position this is already a vector 2 and it fits perfectly into this method call right here and then next we need to provide the mouse's position the mouse's position can be grabbed from m state which we have already updated so all we have to do is say m state dot position dot two vector two so don't forget these two extra parenthesis right here m state.position.2 vector2 will grab the vector2 position of the mouse therefore this entire call right here will grab the distance between target position and mouse's position and it'll store that result in mouse target dist which is perfect now we can actually populate this if statement all we need to say is if mouse target dist is less than target radius and that's enough to do this and here's why having a variable or constant for target radius is useful if the radius ever does change or we use a different sprite for the target where it no longer equals 45 all we have to do is change this one value right here we don't have to go through our code and find all of the 45s and change them to the new value it's all stored right in here so it's very convenient now if this if statement in here is true that means that the mouse is on top of the target because the distance between the points is less than the radius so at this point we can increase the score score plus plus so just to clarify some things we have this nested if statement here we have an if instead of an if the way this will work is that the update method will start this will start it's going to reach this if statement and ask this question if this question is true if both the button is pressed down and m released is true then it will go inside these brackets here perform this calculation and then ask this question is mouse target dist less than target radius and if it is it'll increase the score no matter what the outcome of this though m release is still going to be set to false so that means that the mouse click logic that we did in the previous lecture still holds true even if the mouse isn't on top of the target the only thing that the target calculation does is determine whether or not the score increases here with that done let's go ahead and save and run in order to test this out now if i click outside of the target nothing's happening the score is not increasing but if i move over to the target and click on it it works sometimes you'll notice that parts of the target do work but like this bottom right portion doesn't and this has to do with the point that's actually being considered the target's position you'll even notice that you can click a little bit outside of it as well that's because when drawing a sprite to the screen its position by default is the upper left hand corner of the image so our target position vector 2 is actually pointing at this point right here the upper left portion of this image when in reality we made our calculation based off of the center of the target so there's a misalignment there it thinks that this point here is the center of the target which is why i can click around this circle kind of right here the solution to this is to kind of move our target draw to the left and up so that it lines up with our target position in other words move the center here over to where the actual target position vector 2 is pointing there's a pretty easy fix for this all we have to do is go down to our draw method where we draw the target sprite and instead of just drawing target position we need to get a little bit more creative instead we need to get rid of this and again do a new vector 2. this time though we're going to be utilizing the values from target position but adjusting them a little bit i'll show you we're going to do target position dot x for the x value and target position dot y for the y value of this vector 2. but now we need to do that offset that i was just talking about we need to decrease targetposition.x by target radius and we also need to decrease target position dot y by target radius and i know this looks a little bit strange but the resulting vector is one that moves the sprite to the left by a target radius and up by a target radius so that the resulting position lines up with the target position vector perfectly and we can test this out i'm going to save and we'll run and now i can click anywhere on the target because now target positions vector corresponds to the center doing this little offset with minus target radius was enough to move the sprite up and over so that it lines up perfectly and that's enough to fix this so now that our target is able to be clicked on let's start making a game out of this by making it jump around whenever we shoot it when we shoot the target we want it to jump to a brand new random position somewhere in the game window we can do this by utilizing the random class in order to use this though we need to add a new namespace to the top of the file see up at the top here we have a few lines that say using and then sum package name these are called namespaces they're a collection of tools that we can include into our file and use the ones provided by default are xna namespaces or ones that we need to make games with monogame we're going to add one more at the very top we say using system with a capital s in system this system namespace has the random class that we need so when we have this using system namespace added we'll be able to access it now we're going to go back down to update where we increase the score now we want the target's position to change whenever we increase the score so it makes sense to do this here the first thing that we want to do is create our random object which is what we use to create random numbers this is done with random we'll call the object rand equals new random so just to clarify random is the name of the class we're naming our object rand and to make instances of objects you do equals new random and with this rand object created we can use it to generate the random numbers so in these next lines down we're going to change the position of the target keep in mind that it's here that we just increased the score so again this is the right place to do it let's start things off simple first and instead of using the random class to do this let's just test this out and change target position dot x to just 100 and then target position dot y also to 100. so whenever the score increases we're also going to change the target's position to coordinates 100 100. let's save and let's test this out so when i go to click on the target it jumps up to this position more specifically this is position 100 100. however whenever i keep clicking on it nothing changes the target doesn't jump to any other position and this is why we need to utilize random numbers so that it changes positions every time we click on it so to actually utilize this rand object let's change it from just setting x to 100 to instead setting it to rand dot next and in these parentheses here we're going to provide a range of numbers that the randomness will choose from we'll do a range somewhere between 0 and 200. so by saying rand.next and providing 0 to 200 it'll choose some random number between 0 and 200. keep in mind that 200 is not inclusive so it's actually 0 to 199 and let's actually do the exact same thing for target position dot y and let's try this one out now when i click on the target it's jumping to a new random position now which is starting to get to where we want however you'll notice that it's kind of clustered in this upper left hand corner of the window and this is because the range that we chose was somewhere between 0 to 200 which only goes out to about like right here and the y value is also only zero to two hundred so it's only going to jump to a position somewhere in this square in the upper left hand corner when really it would be best if the target would jump anywhere in the game window completely to make it be the entire game window we just have to change it so that the random number it chooses is somewhere between zero or the left portion to the whole width whatever the width of the window is and same with the height 0 to the whole window height that way that the coordinates it chooses will be anywhere on the game window so to change that maximum width that it could be instead of saying 200 we need to find the width of the game window and this 200 will need to be the height for the game window we can get those values very easily they're immediately available if we do underscore graphics dot preferred back buffer width this graphics object is provided by the template automatically and by saying graphics.preferredbackbuffer width that gets us the width of the game window and for y since we need the height we can do something very similar graphics dot preferred back buffer height so now the x value is going to be set to some random number between 0 and the width of the screen and the y value will be set to some value between 0 and the height of the screen so in the end the target can jump to any position on the screen and let's test this out if i click there it is we can see that it's going pretty much anywhere on the screen so it's a lot more balanced it fits the whole game window that about wraps up this introductory tutorial on monogame we've only scratched the surface of what we can do with this game framework if you'd like to dive deeper be sure to check out my full course on udemy called monogame introduction to c-sharp game programming this course features all the footage from this video but with so much additional content we add more to the shooting gallery game where we put in a timer and add the crosshairs and from there we go on to create two full additional games first being a spaceship and asteroids game then moving on to an rpg style game there are also a total of three sections dedicated to teaching c-sharp so all the necessary coding skills are available here as well there's a link in the description to this course where you can find more information about all the topics covered also using this link will automatically apply a discount code and by the way all udemy courses come with a 30-day money-back guarantee so there's no risk in giving the course a try if you have any questions leave a comment on this video and if you liked this tutorial be sure to hit the like button and subscribe for more game development content thanks a lot for watching
Info
Channel: Challacade
Views: 12,047
Rating: undefined out of 5
Keywords: c#, coding, game development, monogame, kyle schaub, programming, software, visual studio
Id: sPH-sNTSrhw
Channel Id: undefined
Length: 65min 28sec (3928 seconds)
Published: Thu Jul 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.