hi i'm tim dr t chamelard and i'll be your instructor for this course i'm an associate professor in the computer science department at the university of colorado at colorado springs where i predominantly teach game programming courses but i also teach some general computer science courses as well i'm the program director for our bachelor of innovation in game design and development and i have five and a half years indie game development experience running a company that i started with my two sons my two sons have sort of moved on to other things now so i do my game development when my one man chop burning teddy so why dr t well i am a doctor even though i'm not the kind that helps people and my name is tim so the team makes sense but really the reason is i teach a lot of freshman students and at least here in the u.s students in high school are taught to call their high school teachers mr smith or ms jones and so on so the very first time one of my students raises their hand and says mr t mr t everyone knows how wrong that is in case you need a visual reminder i'm dr t i'm not mr t okay this is a four week course and for three of those weeks the first three weeks the graded work is automatically graded programming assignments and that's worth 75 percent of your grade those three programming assignments there's also a final exam worth 25 percent in the final week and don't be alarmed by that it's really just a big quiz with a few questions to make sure you've internalized the stuff from the course there are also 13 exercises that aren't worth any points but they're really important if you need some additional practice with c plus or unreal engine or both and there are also some practice quizzes sprinkled throughout the course as well so the lessons that you'll have in this four week course include getting started and your first c plus code in the first week in the second week you'll learn about data types variables and constants in the third week you'll learn about classes and objects and in the fourth week you'll explore unreal engine basics and you'll have a finishing up video i assume you have previous programming experience pretty much nobody does c plus as the first programming language so i'm assuming you're coming into this course with some programming experience i don't assume you have any unreal engine experience we'll start with unreal engine from the very beginning and in fact i'll cover lots of foundational topics in c plus as well it's just that c plus plus is more complex than many other programming languages so it's important for you to have programmed in something else before the only way is to learn how to program in c plus plus and the only way to learn how to make unreal engine work is to do it right practice practice practice and that's one of the main reasons i've given you lots of exercises as supplemental material for you to get your hands dirty and try to build that muscle memory of how things work in both c plus and in unreal engine frustration is normal even if this is your second or third or fifth programming language it's common to get frustrated with either c plus plus or unreal engine and that's just a natural part of the learning process so try not to get too frustrated even though you know it is going to happen to probably every single one of you when you get stuck remember that there are lots of discussion forums or remember for the very first time i'm telling you now there are lots of discussion forums that you can join in on this course and of course you can always search the internet as well to try to get solutions to your problems so i hope you have a great time in this course i hope you learn a lot and it's time for us to get to work this is the totally optional don't watch it if you don't want to meet the instructor lecture i'm tim dr t chamelard and i grew up in a small town in southeastern massachusetts named norton and after high school i went off to georgia tech to pursue a bachelor's in electrical engineering degree but i was only at georgia tech for a year so if you'd like pause the video and guess for why i only stayed for a year and then continue as one of my past students said i left for the love of a good woman so my girlfriend was in massachusetts georgia tech is in atlanta georgia and that was too far for me so i spent about a year and a half putting the stuff into boxes and handing it to the ups guy and then i am listed in the us air force went off to basic training went to technical training school and after about four months in the air force i got married so pause the lecture again if you'd like to decide whether that was the same girl i left georgia tech for or somebody else the answer is it is in fact the same woman and we are still married so here we are in the air force we went off to omaha nebraska for our first tour and then after 16 months the air force decided to send me to school full time to pursue a bachelor's degree in electrical engineering at georgia tech so i did get to finish that degree at georgia tech and electrical engineering and then i went off to officer training school and got my commission as an air force officer our first assignment in the air force was at los angeles air force base where i spent four years managing contractors writing software to help us fly satellites particularly orbital software was my general area of expertise we had our first two children both boys while we were in los angeles and i also pursued my master's degree in computer engineering at the university of southern california going to school night finished that tour after four years and went off to the u.s air force academy where i taught undergraduate computer science courses for two years now the air force academy is usually a four-year tour but i only spent two years there so if you'd like to pause the lecture video again and try to guess why i only spent two years go ahead and do so the answer is the air force decided to send me off to umass amherst to pursue a doctorate so i am in fact a doctor of computer science so i don't actually help people and my entire family loved the part in treasure planet the movie where there's a non-medical doctor and he is trying to help somebody who's injured and he says i just sit here and i'm useless and i saw that movie with my entire family at the movie theater and at that line every single person leaned over and looked at me so everyone knows i'm a doctor just not a real doctor okay so i finished off that degree and went back to the air force academy for that full four year tour that i should have had in the first place and then my final assignment was to washington dc where i spent a couple years managing contractors developing web applications and the databases that support those web applications undergraduate computer science courses and undergraduate game design and development courses all of which i created from scratch and in fact we now have a bachelor of innovation in game design and development and i teach many of the beginning and the final course in that particular program and i'm the program director for that program so at this point i exclusively teach game development courses i also spent a year and a half as an indie game developer in a company that i formed with my two sons and that's peak game studios and we did a number of games both on speculation and on contract so here are the games we built on speculation the two images on the left are a game called cat that's based on an actual board game so we got the license from the board game manufacturer and you can think of this as chess with lasers and you can actually download a free version of this game at this point from the burning teddy website i'll talk about burning teddy soon the other screenshot from the upper right is for a game that we didn't quite finish as we shut down the company once my sons sort of grew up and moved on to do other things and that game is called battle paddles and you should think of this as pong with weapons because that's sort of the big idea behind that game we didn't quite finish it but we'll get back to that game as well so on this slide are the games that we built under contract so as a company you know we went we got a contract to build some games and we actually got paid to build them and that was awesome so the two on the left are for educational games for eighth graders the one all the way to the left it was a set of four mini-games to teach about physics and the title of that group of mini-games was physics with neat details and if you think of the acronym for that it's pwned and so of course you know a little tongue-in-cheek game development of course and the lower one was to teach eighth graders about robotics so they would configure a robot with various attachments to go complete a number of missions again there were a few mini games to do the upper right one is something called colorado history arcade we got a contract to teach fourth graders about colorado history and that game was deployed on the pikes peak library district website so all of the games we built as a company except for the colorado history arcade game were using c-sharp we happened to use xna game studio to do that um but now of course we've moved on to unity the company hasn't but i have and so that brings us to this next slide where i tell you i now have a small company and by small i mean just me called burning teddy and i use that company to publish textbooks and online courses and of course also to do game development so that battle paddles game that i showed you the screenshot from i am in the process of porting that over from xna game studio to unity that is about 60 000 lines of code so it's going to take a little while to port but at some point that will be on the burning teddy website burningteddy.com and i'm also working on another smaller casual game that is called balloons extreme and i'll actually post my progress on burningteddy.com as i build that game in unity so burning teddy all the game development i'm doing is actually in unity so when i'm not teaching and i'm not doing game development what am i doing well a number of different things but one of those things is cycling so riding a bike is one of my joys in life i guess so these are my three bikes the blue one is the oldest one and that's really an old bike at this point but i used it to really get into cycling and not racing so much but doing long rides like a number of centuries which are 100 mile bike rides including at the time one of the 10 toughest centuries in the united states and so that century had over 10 000 feet of climbing that's what makes 100 mile bike ride harder than another is you know elevation gain and so i did a number of bike rides the mountain bike the one on the bottom is a result of going mountain biking with some friends one day and i loved it so much that i went out and bought the mountain bike the next day the bike all the way on the right is my triathlon bike so you know being a cyclist i did a lot of long rides i also did a bunch of running including a number of marathons and a running race that goes from the bottom to the top of pikes peak here in colorado springs i did that running race multiple times and once you've biked a long time and run a long time you say well you might as well do some triathlons as well just add a swim and you'll be fine and so i've done a variety of triathlons all the way from sprint distance which are really short all the way up to an iron man distance race i also play guitar i started doing that way back in high school and then gave it up for decades while i was raising my family and doing other things and now i've started up again to try to learn how to do it even better than i used to so moving from left to right the acoustic is a yamaha acoustic that i bought way back when while i was just out of high school the next guitar is a joe strummer replica fender came out with a joe strummer tribute guitar some years ago and that was my starting point but i replaced the three saddle bridge with a six saddle bridge because that's what joe strummer used i got to that relict pick guard from a place called axe stream creations and i even took the stickers that were on joe strummer's guitar and cut them into the shapes that they were worn into by the time joe stopped playing the guitar and affixed them to the guitar in the appropriate places the next guitar is a gibson les paul gold top from a couple of years ago and the one all the way on the right is my most recent guitar that is a fender stratocaster american professional 2 and i didn't have a strat so i wanted to strat but i also couldn't resist getting it in the gorgeous miami blue color really the other thing other than you know interesting like you know reading books and stuff like that the other leisure thing i do is i play video games that should come as no surprise to you and so the question is what kind of video games do i play and you should pause the video guess in your mind what those might be and then you can move on to see a screenshot of what i use to play my video games you can see racing games are my passion so really racing simulations so you know realistic racing games rather than arcadey racing games and if you're interested in all the details of that racing rig you can go to the pdf that i've provided as a resource for this lecture so there you have it none of this has anything to do with course content but it gives you a little more insight into who's teaching you in the course in this lesson we'll set up our development environment and we'll write our first c plus code the c plus plus code you'll write throughout this course will be of two different forms one form will be something called console applications or console apps and these are applications that we run and the output shows up in a command prompt window in windows or it shows up in an output pane in xcode but it's text based output so unless you're writing text-based games this isn't really game development but it is learning to program in c plus plus the other kind of c plus code we write will be unreal scripts so we'll write c plus code that drives our unreal games early on we'll have output in an output log window textual output that we're displaying in our unreal games but as we learn more and more about how to develop games in unreal our output will actually be the gameplay that we implement in our games so what specifically will you learn to do in this lesson you'll learn how to install visual studio on windows or you'll learn how to install xcode on a mac and you only need to do one of those two things if you're using windows you install visual studio if you're using a mac you install xcode then we'll learn how to write a c plus console app in visual studio we'll learn how to write a c plus plus console app in xcode and then we'll install the unreal editor once we've done that we'll implement c plus unreal scripts in unreal both using visual studio and using xcode in this lecture you'll learn how to install visual studio on a windows machine c plus plus isn't available in visual studio on a mac so if you're on a mac you'll be installing xcode not visual studio the big idea though is that throughout this course and other courses in the specialization you're learning some of the c plus programming language both in console apps and in unreal you're not trying to learn about a particular integrated development environment like visual studio okay let's go install visual studio the best way to make sure that you get this installation correct is to follow the step-by-step instructions that i gave you in the setting up your development environment reading so this video is just an extra resource for you but really you ought to just go read the steps there and follow them okay so here we are on visualstudio.com and if you're on a mac leave now you should go install xcode if you're on windows we want to install visual studio community 2019 we do not want to install visual studio code some people seem to want to do that but don't that's not what we want over here on the left we have visual studio and if i hover over this drop down i can pick community 2019 don't pick professional or enterprise just pick community 2019 and download the installer once you've downloaded the executable for the installer go to that location and double click that executable it'll do some stuff and that will bring you to something like this although yours won't say modify or launch yours will say install but i'll click modify just so we can look at the workloads that you should make sure you have installed so you should make sure you have checked desktop development with c plus and that you have checked game development with c plus i know you see some unity and c sharp stuff over here just ignore that we're doing c plus plus and the unreal engine in the courses in this specialization so you need to check those c plus boxes also in individual components you should scroll down to code tools and you should make sure you check help viewer so that you can install local help in visual studio if you want to and then you go over here and you click it probably says install for you and you go here and you just click install and then you wait for what feels like a very long time to get it installed once you have it installed you'll have visual studio installed and you can search in your search box on windows type visual studio and it will bring up a result you can click i've added a shortcut to my desktop so i just double click that to start visual studio but you can access visual studio however you want the instructions for setting up your development environment tell you how to set up local help as well and i strongly suggest you do that but that's your choice to recap i'll remind you that throughout the courses in the specialization you're trying to learn about programming in c plus both inside and outside of the unreal engine you're not trying to learn a specific integrated development environment with that said if you're going to use windows you should now go install visual studio in this lecture i'll show you how to install xcode on a mac i'm using visual studio to record almost all the video lectures and i'm a windows guy so i use visual studio as my integrated development environment but c plus is not available in visual studio on a mac so if you're going to use a mac to learn how to program in c plus in this course then you need to install xcode i want to make sure you understand that what we're really trying to learn in the courses throughout this specialization is how to program in c plus both in and out of unreal engine so we're really learning c plus and c plus plus is 99.9 percent the same whether we're using visual studio or xcode so if you're using a mac you should keep watching to learn how to install xcode on your mac we'll start by opening up safari searching on xcode and picking the first hit select download over on the right you may need to sign in and click download on the right i'll say continue i'll cancel out of this this is the tool i want so i'm going to download which will take a while so wait patiently while that happens and now that that's finished we can actually just close all this stuff out and if you go to the finder and you pick applications and you can see that xcode is here in our applications folder so if we double click xcode we may need to install some additional required components so go ahead and click install fill in your password to authorize this and wait while the rest of the required components are installed and when that's all done you'll have xcode opened up to recap i want to remind you that we're learning c plus both in console apps and in unreal engine games so we're not trying to learn an integrated development environment that means it doesn't matter that the videos are mostly recorded in visual studio because c plus is mostly almost totally the same across those two environments with that said if you're on a mac you should go install xcode now in this lecture you'll learn how to create your first console app in visual studio and even if you're planning to use xcode you should watch this video because i cover some of the basic programming ideas in c plus plus that you need no matter what development environment you're using speaking of development environments when we develop software we usually use something called an integrated development environment and it's integrated because it lets us both type in our code both it lets us type in our code and build our code and debug our code if we need to and run our code and so on when you're on windows at least in this course you should be using visual studio and if you're on a mac in this course you should be using xcode so despite the fact that almost all the videos will be recorded using visual studio that doesn't even really matter because we're learning c plus in console apps and in unreal games so we're not learning an ide so it doesn't matter that visual studio is the one i do it all in even if you're on xcode with that said let's go build a console app in visual studio okay i've started up visual studio and you won't have a big list of recent projects you've been working on so you can ignore that part we're going to create our first console app so over here on the right the bottom option is to create a new project and i'll click that and we come to recent project templates and you won't have the c-sharp stuff here either or even this dll for c plus you'll probably only have the windows desktop wizard but that's what we want to pick so i've selected it by left clicking it and then we say next and now we give it a name and i'll call this first console app and i'm just going to save it in the default repos folder but you can click here to browse around your computer to store it wherever you want it's important for you to remember where you store your projects because for the graded work in the course you'll have to upload particular files and you have to know where to go find them so this will store this project in a folder called first console app in my repos folder as you can see in the location but when you pick a place to store it remember where you stored it okay i'll say create we're going to leave all of this just the way it is and i'll say ok and here's what we get for our template console app code there's lots of descriptive stuff in here that will delete but the first thing i'm going to do is up here at the very top i'm going to replace this with the standard copyright notice that we'll see when we do unreal engine projects as well so that's the standard copyright notice that i include in my unreal code and this stuff down below says here's how we run the program here's how we debug the program and we won't worry about debugging yet we will run it soon it says use the solution explorer window to add or manage files and that's over here over here on the right is the solution explorer and you'll typically expand source files so that you can see your c plus file so c plus source code files come with two extensions in general cpp is c plus plus and that's what we'll use for a while and later we'll also discover that c plus plus often has header files as well but we don't have any header files in this project and that's fine we aren't going to be using source control the output window is down here this tab let me magnify for you this tab right here is the output window i'll keep it magnified for a while the error list window to view errors here's the error list window we don't have any errors yet and then there's some other descriptive stuff that we don't actually need to use so i'm going to stop magnifying again and i'll delete this stuff i'll zoom in on the code so what is the structure of this code we got we have this comment at the top that is that copyright notice we have something called pound include and we use pound include to include essentially libraries that other people have written that will help us write our c plus code so we are including the i o stream or input output stream library so that we can use the functions that are in that library this right here is called the entry point to our application this is what's called a function in c plus plus this function has two components the one on the right is the name of the function so this function is called main and the one on the left is called the return type for the function so we will learn as we interact with c plus plus functions that some functions many functions return something when they're done executing and this tells us what the main function returns i'm going to add a javadoc comment at the top of this code and javadoc comments are used to automatically generate documentation for the code that we write so it's a really good idea to comment every function we write and to comment every class we build which we'll get to soon with a javadoc comment i'm going to remove that at brief at the beginning the visual studio environment adds that for me but i don't actually want it because i'm going to use the commenting style that is standard for unreal engine projects i know this is a console app but we want to just be consistent with the style that we use for commenting and capitalization and everything across our console apps and our unreal engine games in the courses in the specialization so we'll just follow the unreal engine naming guidelines and commenting guidelines coding standards if you will and we'll do that even here in our console apps so i will just say prints something and this at return says here's where we should provide a description of what gets returned from this function so i'm going to put here that this returns the exit status it's basically an integer that says did the main function run to completion fine or did it crash along the way we can actually run this code right now because we got this line of code in our template before we do let's actually compile the code first so up here on the top menu bar we can select build build solution the hotkey on my computer is f6 i have seen it be a control shift b combination i've seen it to be f7 so the first time you do this you'll need to do it this way to figure out what the hotkey is and if you always when you use f6 like i do then you can google how you can change these shortcut keys okay so i'm just going to click build solution and i'll zoom in again and down here in output you can see i got a build one succeeded so that's great this built just fine that's nice there were no compilation errors and now i want to run it and up here on the top menu bar we have a debug option and we can either start debugging or we can start without debugging there will be times that we want to debug a console app but usually we just want to run it so i will control f5 and as you can see it prints out hello world and now i can just press any key to close the command prompt window so how did that work we said here that we want to send something to the output stream and this first part is called a namespace this is the standard namespace and we don't have to pound include it or anything if we use other namespaces we'll have to pound include the library that includes the namespace but here we're just saying this stream is a part of the standard namespace then we put two less than signs because you can think of this as sending the stuff here into the stream that's a good way to think about this so we're taking this which is called a string literal stuffed between double quotes is a string literal we're saying send that string literal to the output stream and the default output stream is the command prompt window so we can just do it this way and it will print this to the command prompt window a couple of things we could up here we could say using namespace standard and then we could just do this and it will also work fine i'll show you like so the reason people use namespaces is in case two different namespaces have something that has the same name and we use the namespace to disambiguate which one we're talking about i'm going to always just use this notation but know that there is a shortcut for doing it a different way there's one more thing i want to show you this slash n here is called an escape sequence and it prints a new line if we didn't have this and i ran you can see that this message that says we exited with code zero appears smashed up against what we output and i don't like that so i like the new line instead you may have noticed or you may not have noticed i'm just ctrl f5 without building because if i've made changes to my code visual studio will automatically rebuild when i run and there's that space i want another way that you will regularly see c plus programmers moving to the next line in the output is doing something like this so this is the end line that we're also sending into the output stream after this and i'll run it again to show you that and it works exactly the same way now i said it works exactly the same way that's not strictly true under the covers so i am going to use this instead which is in fact a little more efficient than using standard and line and that's it that's our first c plus console app using visual studio to recap you saw in this lecture how to build a console app in visual studio and i'll remind you that you can use either visual studio on windows or xcode on a mac to do all your c plus development in this course i'll provide all the course materials lecture code exercises programming assignments everything both for visual studio and for xcode so it doesn't matter which one you end up using in the course last time we saw how to create a c plus console app in visual studio in this lecture you'll see how to create a c plus console app in xcode i've only picked up xcode and i'm going to create a new xcode project and we're going to build a command line tool and the product name will be first console and now i pick where i want to put it and i'll pick that and then we'll come back and if i select main dot cpp on the left i get my main c plus file i'm going to modify this top part with the standard copyright notice that i'm going to use on the code throughout the course and i like to have my open curly brace on the following line not at the end of the line and i want to include those documentation comments that i put in javadoc format so i can use doxygen to generate documentation there's a reading about doing doxygen comments in xcode and i'll type doxy and then hit enter and that's because i created a code snippet in xcode as that reading describes so that it will fill this in when i type doxy and hit enter i'll just say that i'm going to print something and i actually have two parameters here i have rxe command line arguments count and i have another parameter that is argv and that's the command line arguments and then finally i return the exit status for the main function the code i'm inserting is the code that it gave me by default just says hello world and it returns zero as the exit status so if it gets to that line of code the main function executed successfully we need to do two things we need to build our code and we need to run our code and we can do both at once if we just say go ahead and run it will build it first and then run it but i'll show you both steps here so to build you can either use command b or you can say product build and then you wait patiently while it builds and you get a build succeeded hopefully and to run it you can either use command r or product run and as you can see it builds it again and now it's running it or it's getting ready to run it because we need to allow access i put this in my documents folder so i'm going to allow that access and as you can see down here on the bottom right it says hello world and the program exited with exit code zero and that's how you go about creating a new xcode project and writing a simple console app in xcode to recap in this lecture you learned how to create a c console app in xcode and as a reminder even though almost all the videos are recorded in visual studio the c plus ideas are the same in this lecture we'll go through the installation process for unreal engine and even though there are minor differences between a windows installation and a mac installation you should be able to follow the process that i'm showing you here to get unreal installed on a mac just as for installing visual studio or xcode the best way to do this is just to follow the instructions in the setting up your development environment reading but i'll show you some of the steps anyway here so you go to unrealengine.com you can click get started now you want the publishing license which is free for you to use until you start making a million dollars and then you need to start paying a royalty but that's a long way away for those of us who are working through this specialization so you just go down here to download now and you click it and you'll end up downloading an epic games launcher installer you should go to that installer and double click it to get it installed and as the reading says when i did the first installation i got this error message and it's great if you don't but if you do you should follow the instructions in this paragraph to resolve that problem now that you have the epic games launcher installed go ahead and launch the epic games launcher start up that program and you'll get something like this you probably won't have any launch and unreal engine over here yet because you don't have any installed what you'll do is you'll click unreal engine on the left and up here on the top it will say install unreal engine and you should do that and that will get unreal engine installed for you later on if you ever decide to add additional versions of the engine as you can see i have the most recent at the time of this recording engine and an older version you'll just click this plus and it will give you options but it won't include the ones you already have installed so that's how you get unreal engine installed to recap in this lecture you saw how to install unreal engine so now you should go install unreal engine in this lecture you'll learn how to write a c plus script in unreal so let's get to it as you can see i've launched the unreal editor and i don't want to open any of these existing projects i want to do a new one so i'm going to select games here and then click the green next button i'm going to do a blank template and be sure to change over here in the upper left hand option change from blueprint to c plus plus we want to build a project that we use c plus code in not blueprints blueprints is the visual scripting language that you can build lots of really cool unreal engine games with but the courses in this specialization are also teaching you c plus plus so we want our projects to be c plus plus projects sometimes when you first start using unreal engine you get some starter content over here and you should click the icon like this and make sure you're starting with no starter content down at the bottom you can pick where you're going to put the project you're about to create and you can name it so i'll call it first unreal script and i'll create the project now you just have to wait until the editor actually opens and here we are in the editor the first thing we're going to do is we're going to save our map this is the map right here that we're looking at in the viewport you can think of it as a level in your game i'm going to click the content browser tab down here on the lower left and here in the content browser panel i'm going to right click and i'm going to create a new folder now we're using good folder naming conventions for unreal and that means that this top level folder in content should have the same name as my project which is first unreal script then within this folder which i'll double click to open i'll right click and i'll create another folder called maps and then finally i'll either control s or i'll save current and i'll navigate to my maps folder and then i'll save my map i'll call mine map0 and i'll save it the next thing that's really useful to do to help people who might be opening this project like when i save it and you open it up it would be nice if map0 actually automatically opened up in the editor when you opened up the project so i'm going to say edit project settings and on the left i'll click maps and modes and over here in the default maps area i'm going to change both of these to map zero and then i can just close the project settings panel and that way when somebody actually opens up this project it will open up to this map the next thing i want to do is i want to add a c plus script that's going to print a message so i can go up here on the top menu and say file new c plus class and we're going to talk about classes and objects soon but not quite yet so just to know that we need to pick new c plus class and i need to pick actor as the parent class and click next i'm going to call it print message i'm going to make it save in the default folder and i'll say create the class now we'll add a template c plus class to the project for me just like we got a template c plus plus class when we told visual studio to create a console app for us once that's done we want to actually open up that code that was just generated for us if visual studio is already open for you you can alt tab over to it and say reload all and as you can see i forgot to fill up my copyright notice on the description page of project settings so i'll add that and we'll come back so how do we make this script that unreal generated for us print a message in the output log i'll show you the output log soon but we want to print a message to the output log there are a few things that we do first here in this function which is actually called the constructor for this class this is setting a particular value to true which basically says for objects of this class you should call this tick function every frame of the game but we don't need that we're just going to print a message once so we're going to set this to false we won't call the tick function on this object every frame because we're just going to print the message once the place that we're going to print the message is down here in the begin play function which is called when the game starts or when this object is spawned in the game so here's where we'll do it and here's what we do we'll use something called u e log unreal engine log which is actually something called a macro but we can just treat it like a function we can act like we're calling a function here we do however need to provide three arguments to this macro we need to provide the name of a log that we want to log to and we'll just use log temp which is just one of the built-in logs that unreal engine gives us we'll give it a verbosity level which we'll say is warning so that will just really affect what color it shows up as in the log and finally we'll say what do we want you to print in the log we'll use another macro called text because we're going to say we want you to print this text in that log and then we provide a string literal just like we provided when we did our hello world message here we'll be a little less supportive and we'll say hello noob instead but that's what we'll provide as our log message now it's super important to know that if we don't compile over here then when we get back over in the editor this code will not have any effect it will pretend we didn't type anything so the pattern of behavior you should have every time is compile the code as soon as you've typed it and when you see that the build has succeeded we're good to go back to the editor you don't actually have to compile the code as soon as you've typed it but you always want to make sure you compile before you return to the editor okay back here in the editor we still haven't added our script to the map so because it's not living in the map when we run the game the behavior we included in that script won't get executed as the game runs so we need to add the script to the map the way we do that is we click on this folder icon just to the left of content here in the content browser panel and you can pick c plus classes and you can expand this and it has a built-in folder called first unreal script so we'll select that and we see here's our print message script that we just wrote we'll drag it into the map and drop it there and over here in the world outliner we can see that we now have a print message script in our map if i click the output log tab here i'm going to be able to see the logged output when i run my game if you're not seeing the output log you can just say window developer tools output log and if you select that you can drag it and drop it over here and it'll be there until you decide to remove it so i could right click this tab and close the tab but i'm not going to do that because i want it so now i want to run my game i can click the play button or i can alt p and it will play the game and you can see down here in the output log you can see that we got our hello noob message and to stop running the game we just hit escape or click the stop button up here and now we're back to our map we have some changes to save right we added our script into the map and by the way once we did that that script is called an actor it's in the map as an actor so we'll save current you can control s or click that button and now we're all done saving this first unreal script project to recap you can write your c plus scripts in unreal using either visual studio or xcode and an important thing to remember is you need to have your script in the map for your scripts to actually run last time you learned how to write an unreal script in visual studio and even if you're using xcode in the course you should go watch that video anyway because it talks about how scripts work in unreal now let's go write a c plus script in unreal using xcode as you can see i've created a new first unreal script project and i did all the map folder stuff and so on and i created a new c plus plus class called print message and if i double click a script it gives us the dot h header file in the dot cppc plus file and i don't actually want either of these so instead i'm going to say file open xcode because i prefer having the full xcode environment i can now navigate over here on the left into games first unreal script so this is my project code gets saved in the source folder in the first unreal script folder and here's my print message c plus plus file as usual i'll change this to false and down here i'll print a message and i'll do that in the usual way and i'll even print the same message i used in the previous lecture now i can build using command b and you don't have to worry about those error messages that are showing up you just need to wait patiently until you get the build succeeded message now we can come back to the unreal editor and we'll add our script into the map and finally we'll alt p to run the game and if we look at the output log we see it says hello noob just as we expected so obviously doing your first unreal script with xcode is remarkably similar to doing your first unreal script with visual studio except that we need to explicitly open xcode to get the full environment rather than just double-clicking the script to recap in this lecture you learned how to write an unreal script using xcode what will you learn about in this lesson you'll learn how bits are used to represent information you'll learn what data types are you'll learn about some of the c plus data types and you'll learn the difference between a variable and a constant in this lecture we'll talk about how we can encode things in a computer using bids and we'll also talk about how many bits do we need to encode a particular number of unique things so everything in the computer is in binary and what's binary binary is base two why do we care about that we can use ones and zeros to represent anything in a computer we can represent numbers we can represent characters we can represent pictures we can represent sound we can represent anything with zeros and ones that raises the question though first how do we do it and second how many bits do we need to represent a particular number of things and that requires me to tell you a christmas story so my family one several years ago were trying to figure out who gets to open the first present that's part of our tradition of christmas and we wanted to do it with coin flips so we were thinking about how many coin flips did we have to do to pick out of four people one of my children was not there yet out of four people how many coin flips did we have to do to figure out who opened the first present now me and my son a computer scientist came up with one answer and my wife and daughter came up with a different answer so you should pause the video for a minute and think about how many coin flips you would need to do to actually pick from four people the person who gets to open the first present once you've figured that out go ahead and unpause the video and i'll talk through the two different solutions that we came up with that christmas morning okay one of the common solutions that we might use would be to have a tournament this is sort of a standard structure that you see in you know playoffs and hockey or some other inferior sport to hockey so you have these ladders if you will and you have a plays b and somebody wins and that would be one coin flip c plays d and somebody wins and that would be another coin flip and finally the winner of those first two games if you will play with one more coin flip so you can do that with three coin flips that's a very natural normal way to come up with a solution to this problem however i'm going to be very dramatic here we can use the power of binary and we can actually encode a b c and d each of those four different things by using two bits and so if we encode a as 0 0 and b as 0 1 and so on we can actually determine who wins with only two coin flips and i will freely admit that we spent far more time talking about this than it would have taken to do a third coin flip but that's kind of how my family works but the next question is how many bits do we need to represent a certain number of unique things this was a really interesting conversation because it was how we go about encoding stuff in the computer but if we're going to encode stuff how many bits do we need to encode stuff so let's say we have one bit we can encode two unique values we can have zero or we can have one so two unique values what if we have two bits well that was the example we just did we can encode four different things and if we have three bits we have eight different possible encodings zero zero zero zero zero one zero one zero zero one one one zero zero one zero one one one zero and one one one and let me fix my glasses i was counting up in binary but those are the eight different combinations we can get with three bits now some of you may have already realized that if we have one bit we can represent two things and two to the power of one is two if we have two bits we can represent four things and two to the power of two is four and if we have three bits we can represent eight things and two to the power of three is 8. so now i'll show you a slide with the biggest font you'll see throughout the course the relationship is 2 to the b equal n so if we know how many bits we have we just raised 2 to the power of b and that tells us how many unique combinations of those bits we get which tells us how many unique things we can represent if you know how many things you want to represent you can use the inverse relationship right we can take the log base 2 of n to calculate b but i'll tell you i personally never do that right i i sort of go through the process well you know i'm trying to represent 12 things how do i figure that out is three bits enough no two to the third is eight is four bits enough sure two to the 4th is 16. we can never use partial bits there you can't say oh i need 3.7 bits it's not how it works you only get whole bits but i don't usually use the log base 2n equation i just usually use two to the equal n and work my way into however many bits i need so that's it for this lecture the two powerful ideas are we can encode anything with zeros and ones in a computer and we have to because computers use binary and we have this relationship this 2 to the b equal n that will tell us how many bits do we need to encode n unique things recall that last time we discussed the fact that everything that's represented in a computer is represented in binary that gives us a problem though so what does 0 one zero zero zero zero zero one mean well it can mean a lot of different things it could mean the number 65 if we're talking about the binary number system it could mean capital a if we're talking about ascii representations of characters it could mean the red component of a pixel if we have eight bits for the red component of a pixel so a sequence of ones and zeros can represent a whole bunch of different things how do we know which thing this sequence of ones and zeros actually represents a data type tells us how to interpret the bits at a particular location a data type also will tell us the valid operations that we can perform on those bits in that memory location for example it doesn't make any sense at all to take a character and add true or false to it those are not compatible data types for addition okay so here is a conceptual representation of memory the numbers on the left are the addresses of locations in memory and the contents of the boxes on the right are the strings of ones and zeros that are in those locations when we program we're actually interacting with memory where we're putting stuff into memory and we're taking stuff out of memory and it would be nice if we could get a memory location that we could refer to by name instead of by memory address because memory addresses in our programs are really horrible to look at so we want to refer to this memory location by a particular name and we also want to be able to tell how should we interpret the ones and zeroes at that memory location there are multiple ways that we can actually get a named location in memory that is interpreted properly and those two ways are variables and constants when we declare a variable we provide the data type so that tells us how to interpret those ones and zeros and we provide a variable name and that is the name that we'll use to refer to that memory location instead of using the actual memory address optionally for variables when we declare one we can also provide an initial value for that variable we can set the zeros and ones in that memory location to a particular value that's called initializing the variable we can also declare a constant and a constant we provide the data type we provide the keyword const we provide the data type we provide the constant name and we provide the value and the value is not optional for a constant the value has to be provided when we declare the constant the difference between variables and constants is variables can be changed by our program as our program executes and constants can't they have to be wait for it constant as our code runs to recap in this lecture we learned that a data type tells us how to interpret the bits at a particular memory location and tells us the valid operations for the bits contained in that memory location and we learned that we can use variables and constants to get named locations in memory with data types that control how their contents are interpreted and the operations we can do with them in this lecture you'll learn about some of the data types we use in c plus to represent integers so what's an integer an integer is a whole number it's a number with no decimal point no fractional part like 0 or 42 or negative 11. some of the common data types we use in c plus to represent integers are short int and long long each of those data types has a different number of bits used to represent that data type and what does that tell us well we know 2 to the b equal n so it tells us if we have more bits we have more whole numbers that we can represent we are typically going to be using int through the courses in the specialization but it's important that you know that there are other options the operations because remember that's the other thing that data type tells us the operations on these data types are mostly as you'd expect except for division and i think it's a good time for us to go take a look at some code to see how all that works i've started visual studio and i'll create a new project and again i'll use the windows desktop wizard which we'll always use as we're building c plus plus console apps i will call this integer data types and i'll say okay here and here's my template code again i'll just type in my copyright notice and then we'll come back okay this time i'm not printing out this message what i'm going to do is i'm going to have a total seconds played as an integer and so the first thing i do when i'm declaring a variable is i put its data type and since this is an integer i'm going to use int the next thing i put is the name of the variable and there are a number of different naming conventions people use when they name variables i'm going to show you several of those ending with the one that we'll use throughout the courses and the specialization so i'm going to have a total seconds played here one thing people use is something called snake case like that so it's called snake case because the characters are higher than the underscores so it looks like the curves of a snake we're not going to use that another style people use is this which is called camel case because it has capital letters that you can envision as humps on a camel's back we're going to use this style which is called pascal case because in ancient times there was a programming language called pascal and this was the standard way we would name variables in pascal even more importantly for us the unreal engine coding standards say that people who are programming in the actual engine code base name variables using this capitalization scheme so we are going to use pascal case for our variables you will look at c plus plus code on the web and elsewhere and you'll see all kinds of different naming conventions for variables and the bottom line is if you're doing personal projects you use whatever coding standard you want if you're working at a company you use whatever coding standard the company uses and so we're going to use the unreal engine coding standards the other thing i want to do though is i want to initialize total seconds played to be a hundred i want to use a hundred one of the common ways you'll see this done is with something called an assignment statement so we can say equal 100 like this and it will give the total seconds played variable a value of 100 and this is the syntax that's used across many many languages we're going to use a different syntax here that is only available to the best of my knowledge in c plus we're going to use something called a braced initializer and that spacing happened visual studio fixed that for us this is another way to actually initialize a variable the reason that i want to use a braced initializer here i decided personally i wanted to use a braced initializer here is because if i make a mistake here i know this is an integer but if i make a mistake and i type 100.3 and i try to compile when i do that i actually get an error message that i cannot convert from double to int because it's what's called a narrowing conversion i am converting a bigger data type into a smaller data type and because 2 to the b equal n we know that we will or could lose precision by doing that so this is an error it's not allowed i'm going to keep the zooming in turned on for now if i do this if i use the assignment statement and i f6 it builds fine it doesn't complain at all to me that there was a problem if i come over to the error list i can click this warning box that tells me that you could lose data doing this but this is a warning not an error and this is a bad enough issue that we actually would prefer our code doesn't compile at all so i'll turn off the magnifier and i'll change this back to a braced initializer and i'll get rid of the 0.3 as well so sometimes this helps us and sometimes we don't care but when it helps us by giving us a compilation error we can then fix our code rather than just potentially ignoring warnings that we say well whatever it compiled let's move forward okay what we're going to actually do is we're going to calculate minutes and seconds plate and then we're going to print the results so calculating minutes plate we will use another int all of our results will be int's here so we'll say minutes played and we can use the fact that division on integers does that quotient and remainder division to say this is total seconds played and you can see by the way that this intellisense is popping up and i can just hit tab and it will fill that all in for me so it's total seconds played divided by 60. and let's print those results to see them so remember standard c out we'll print a label to say what number we're actually outputting and i will say we typically will label our output in console apps when you're writing code to submit to the automated grader you won't be labeling your outputs you'll just be printing out numbers and that way the automated grader can just compare numbers people who decide to have different labels for their output make it really difficult for the auto grader to say oh that's correct it's just a different label so when we write code for the autograder we won't label our output but in our typical console app we will okay so i've sent that minutes played colon space string literal to the output stream now i want to send minutes played the value of the variable to the output stream and then i want my new line character so i'll compile to show that this compiles fine and i'll show you over in the error list that we are warning free we have zero warnings and i'll run the code and you can see that minutes plate is one just as we would expect so now we can calculate seconds played and that's total seconds played and i'm getting ready to type 60 again but i'm uncomfortable doing that because 60 is what's called a magic number and although it's easy to tell here what we mean by 60 it would be much better for readability of our code and for maintainability of our code to declare a constant for the number of seconds per minute because that's what this 60 means so let's come back up here and this constant can go anywhere it could go right here after this comment it could go after the variable it's just personal preference i declare a constant by putting the keyword const this one's also going to be an int minutes per second and i can use braced initializers for constants as well but now i can use the constant in both these places and it makes it more readable and makes it clear what we're doing i will say that that may not feel super compelling to you at this point but if you thought of this constant as something like damage per hit if we use damage per hit throughout our code and say it's 10 if we decide to change damage per hit to 5 instead all we have to do is change the value of the constant and it works everywhere throughout our code if we don't do that we have to look at every 10 that we can find in our code and think about whether that 10 means damage per hit or seconds for cooldown or score per destroyed teddy bear or whatever and only change the tens that mean damage per hit to 5 and so using constants is a great way to sort of consolidate that number in one place and make our code readable and make it so that if we decide to change that number we can easily do so i know we're not going to change the minutes per second but that's the big idea behind using constants so you might as well start doing that now of course we're going to print out seconds plate as well and when i control f5 you see i made a mistake it is certainly true that minutes played is one but seconds played is not one part of the moral of the story is you should know the answer before you run your code to make sure it runs properly of course what i wanted to use here instead of divide was percent to get the remainder so when i control f5 i get one minute played 40 seconds played which is the correct answer and that's our example for using integer data types you can see that visual studio is somehow getting confused up here with these red squigglies around our comment it's okay don't worry about that typically red squigglies mean you have a mistake somewhere but this compiles fine it's really strange because i can make those red squigglies go away by doing this using the assignment statement rather than a braced initializer for my constant and it runs perfectly fine and it will even work fine with no squigglies if i do a braced initializer here it's just that it sometimes gets confused and puts those red squigglies so let's not worry about those as you can see they're not there right now the big important thing is that when we compile we get output that says build succeeded or up to date which means it didn't really change anything of course you would have realized when i was declaring my constant as minutes per second that what i actually meant was seconds per minute and i put a banner in the video there but we can easily fix this and this is something you should do as a programmer we shouldn't just leave it this way because it's horribly misleading to have a constant called minutes per second that actually means seconds per minute here's how we can do it we can right click minutes per second and the second option is rename and i can just type seconds per minute and i can preview it if i want and say apply and it changes all the occurrences of minutes per second to seconds per minute instead so when i run my code now it works exactly the same as it did before but we have a constant that is declared to be an appropriate name and that's what we should do as good programmers we have a few more things to talk about before we're done with this lecture so let's say you have an int variable and it has a value of one and you add one to it what do you get pause the video think about it and then come back the answer is two isn't this great you're taking a college level class and one plus one is two that's not the big idea here's the big idea say you have an int variable that has a value of 2 billion 147 million 483 647 and you add 1 to it what do you get you actually get negative 2 billion 147 million 483 648 and why does that happen well i've added a reading you can read that really explains in agonizing detail why these integer variables wrap around but this is because 2 to the b equal n and for ins where we have both negative numbers and positive numbers if we're at the maximum positive number and we add one to it we wrap around and it's because 2 to the b equal n so if we only want to store positive numbers this does not solve that 2 to the b equal n problem but if we want to only have positive numbers we can use unsigned integer data types in c plus plus instead so we only get positive numbers what does that buy us it gives us twice as many positive numbers as we have if we have both positive and negative we don't have to save any bits for negative numbers we still have the wrapping problem if we have the max positive number and we add one to it we'll come back to zero but it gives us more positive numbers and if we're using numbers that we know will never be negative it's reasonable to use the unsigned data types and those are unsigned short unsigned int and unsigned long long and there are some other c plus integer data types that we haven't talked about and we won't really worry about so to recap in this lecture you learned about a number of data types we can use in c plus plus to represent integers and i said we were recapping but i have to say that you might think that that rapping thing that i talked about is just like a geeky academic thing and doesn't matter in practice but i will say that in grand theft auto 5 rockstar used an int to represent how much money people had earned and somebody because you will learn that players do things you never expect them to do somebody got really really rich right and he had approximately 2 billion 147 million hundred and eighty three thousand six hundred and forty seven dollars and then he earned more and suddenly he was wildly bankrupt and it's because it's rap so this isn't just of academic interest that two to the b equal n thing really matters when we're deciding the data types for our variables okay now i'll call this the end of this lecture in this lecture we'll talk about a number of the data types we can use in c plus to represent floating point numbers and floating point numbers are numbers with the decimal point right they have a fractional part before we talk about specific c plus plus data types we should talk about a big problem that we have because numbers in the real world particularly numbers that we call real numbers those numbers that have a decimal point have an infinite number of values so we know that 2 to the b equal n so when we try to translate or represent those infinite numbers in what's called the discrete domain using bits we can't do it unless we have an infinite number of bits because the only way to represent an infinite number of unique things is with an infinite number of bits what we do is we decide that we are going to represent a range of real numbers with the same sequence of bits in the computer and when we do that we lose some precision right we've got sort of rounding we're rounding every single one of these real numbers to a particular floating point number in the computer in general if we use enough bits for whatever application we're doing that works out to be okay but it's important for you to understand the difference between real numbers in the continuous domain and floating point numbers in the discrete domain inside our computer okay so for floating point numbers there are a number of data types that we regularly use they're float double and long double and floats are what we will typically use throughout the courses in this specialization each have a different number of bits allocated to them and as we know that means that the data types with more bits can represent a wider range of numbers the operations on these floating point data types are pretty much as you'd expect so let's actually go take a look at some code that uses floating point data types i've already created my visual studio project and i called it floating point data types and i've added my copyright notice and my javadoc comment above the main function so here's what we're going to do in this code we're going to calculate and print points per second and i know some of you may be like well no it should be dps damage per second but let's say i played an action game and i earned a score and i played for a certain number of seconds and now i want to calculate and print the average so i need a variable called score that's whatever score i happened to score during that gameplay session so let's say that score is 1360 and scores are typically integers so i'm going to make this an integer and let's say that i kept track of the total seconds played as an integer as well just as we did in our integer example so int total seconds played and let's say that was ten thousand seconds that's not too bad and now i want to calculate and print my points per second let's start by doing it a naive but feels correct way to do that calculation i know that i want to put this into a float because i'm going to divide score by total seconds played and so i know that my numerator is going to be smaller than my denominator so my points per second is going to be some decimal number less than one so i'll say here points per second and i know i'm making a mistake here but i'm going to do it anyway is score divided by total seconds played and then i'll print that out in the typical way with a label because i'm not submitting this to the auto grader and i don't think i want to say pinte i think i want to say point per second and i'll send the value of the variable to the output stream as well and my moonlight character but then when i run it i end up with zero as my points per second and i end up with my zero because here i'm dividing an integer by an integer so this division does integer division which as we know gives us the quotient and if the numerator is smaller than the denominator the quotient is zero now you could say well i know how to solve this i'll just make score of float but that doesn't make sense if you think about this score is a whole number we know that from our game so changing the data type of score to be a float just to make it all work is not intuitive based on how the game actually would play so we don't want to do that same argument for total seconds played i said we stored that or kept track of that as a whole number so when you declare variables they should always be the correct data type not an incorrect data type just to try to trick the compiler to do what you want it to do there's a better way to solve this problem and the better way to solve this problem is to make one of these or both but one will be sufficient be treated as a float and the way i'm going to do that is i'm going to do something called a typecast so i'm going to say treat score as a float just for this calculation this is a temporary thing it doesn't change the underlying data type of score score is still an end it just says for this calculation treat score is a float as soon as we do that this division becomes floating point division and that's just what we want because we have a fractional part in our division result so if i control f5 now you can see points per second is 0.136 and hopefully you can see that that is the correct answer based on score and total seconds played so the important lessons from this short example are we always want to declare variables to be of the correct data type we don't want to try to trick the compiler we just use the right data type and we want to type cast if we need to to force the math to work right i will say before we leave the code that you might be tempted to do this you might say well if type casting score is good then typecasting the whole result must be even better but that's not true if i control f5 you'll see points per second is back to zero because what happens is this part does integer division so you get zero and then you say treat that zero as a float but sort of who cares right so the other moral of the story here is that when you do typecasting you should typecast as close to the place that you need to typecast as you can instead of saying i'll just typecast the whole result that doesn't work in this case we need to typecast one or both of these variables and it's your choice we could have typecast this to float instead we could have typecast both of them to float but doing just score makes the division be floating point division which is just what we need in this particular example to recap in this lecture you learned the difference between the continuous and the discrete domains and you also learned about some of the floating point data types we can use in c plus in this lecture we're going to explore a little more deeply how to read documentation and i know no one ever says i want to develop games so i can read the documentation but this is really a critical skill for programmers throughout your programming life you'll spend time reading c plus documentation or unreal engine documentation maybe not even through your programming life through the courses in these specializations but you have to be able to do it for code that other people have provided to you watching me do it is not going to help you learn how to do it you're just going to have to practice and practice and practice but you're going to have to do it to be able to become a good programmer in a particular domain let's go solve a small problem that requires us to get some practice reading documentation here is our template console app with the copyright notice added and the comment added above our main function and the comment that says what we're going to do in this particular chunk of code and what we're going to do is we're going to calculate and print the cosine of 45 degrees so we'll start by declaring a variable that holds the angle and i have a choice of data type here right i can do int if i want to do whole numbers for degrees i can do float if i want to do floating point numbers for degrees so i think i'll make this a float and i'll call it angle and i'll initialize it to 45. so now i have an angle in 45 degrees and i need to figure out how to calculate and print the cosine of course the first step in that is to calculate the cosine and this is where reading documentation helps us so if you're using visual studio and you've installed local help then you can just say help view help and it's reasonable to gas that cosine the standard abbreviation for cosine will be something we can use so if we search on cosine we'll just click that first hit and we discover that there are a number of versions of cosine so here are those three versions of getting a cosine that we could use we have a cosine function that takes a double as an argument it's a parameter on this side but it's an argument when we call it and it returns a double we have a cosine f that takes a float and returns a float and then we have cosine l which takes a long double and returns a long double in all of these for the argument we could pass in an int for example and it would get promoted to the appropriate parameter type when we call the function so we don't have to worry that we can only explicitly pass a double to cosine here for example we could pass a float we could pass an end we could pass any of the smaller data types and they get promoted to a double let's use this one because we're going to try to use float pretty consistently throughout our unreal engine games so we'll try to use floats here and our console apps as well so you've sort of read the documentation as fast as you can because you didn't go into game development to read documentation so you read this parameter x and you say it's the angle and you say great i know what to pass in you stop reading right there and you leap back into your code if you don't have visual studio local help installed or you're working in xcode the c plus reference web page is a good place to go to find out information about c plus code think of this as the c plus plus documentation that's authoritative and reasonable and so on so if we go up here in the upper right hand corner and do that same search on coase and hit enter we find this which also gives us similar documentation right we have this one we have the double one we have the long double one and there are some other versions listed as well but essentially we're looking at approximately anyway the same documentation and again you'd say okay the parameter arg is a value representing an angle and you're excited to get back to work so you get back to work i'm going to put the cosine into a variable before i print it out that's of course not required we could just print it out directly but we're still practicing declaring variables and assigning values to them and so on so let's do that here as well so i'll call this one cosine and i'll say equal to cos f of my angle and i'll print it out with a label because we're not submitting this to an automated grader so when we run it it says that's the cosine of 45 degrees and we're all excited we say hey that's great we got a number it must be right it's not right it's not the correct cosine of 45 degrees and that reminds us again that when we run our code to test it we have to know what the right answer is to be able to tell if we're getting the right answer and we're not so now our issue is what's going wrong and your first instinct as you look at this code is fairly straightforward it seems like it should work you say i must be doing something wrong i better go back and look at the documentation again when you do you read this entire sentence and it says angle in radians or you look at this documentation and you see it says angle in radians so now we come back here and we realize that the problem is our angle is in degrees and we're calling the cos f function as though the angle is in radians so let's convert angle to radians so we can take angle on the left hand side of this assignment statement we're giving angle a new value and we can say angle times something so you have to know how to convert degrees to radians and it turns out that 360 degrees is equivalent to 2 pi radians so 180 degrees is equivalent to pi radians so if we take degrees and we multiply by pi over 180 we will have converted to radians instead of degrees i'll start by doing it the way you shouldn't do it 3.1415 float divided by 180 and i'll explain why we shouldn't do it that way in just a moment but i'll run the code and we get 0.707 and change and it is the cosine of 45 degrees at least to three decimal places but we shouldn't do this piece we should try to find out if there's a constant that's available to us that represents pi because you have to imagine that people using c plus plus for computation must use pi more than once so somebody somewhere should have declared a constant for it let's go see if we can find it in the microsoft help viewer we can just search for pi and that doesn't help us much let's go to the c plus reference and search for pi and none of those things are helpful and at this point you might say well i'm not getting anything that helps me i should do something else and the something else that you can do that people regularly do is to go google or bing or yahoo or whatever your favorite search engine is you might go looking for pi in c plus plus so let's do that i'll go to google and i'll say pi in c plus plus and see what i can find out and you have to search around a little bit sometimes you can find it down here and this will actually be helpful to us right here so let's follow this link and we can scroll around a little bit and we can see that sometimes some compilers including all the compilers we're going to be use declare a constant called m underscore pi so we can use m underscore pi with a little extra work in our code i will say that searching the internet for help in discovering things like this is a really good technique to use you have to have your internet filter so that you recognize what seems to make sense and what doesn't make us any sense at all but this in fact makes sense so we'll go back to our code and we'll put m pi here just like it was talking about but we get red squiggles and that's disconcerting to us unfortunately one of the side effects of using c plus plus across multiple different platforms is different platforms deal with the c plus libraries in different ways and in visual studio not an x code but in visual studio we need to include a pound define use math defines in our code and we can compile again at this point and we can run again at this point and we see that that number is slightly different from what we had before it's more correct than the number we got previously when we just used 3.1415 because the m pi constant is to more decimal points of precision for pi than just four decimal points of precision so we did a couple of things here we read the c plus plus documentation directly finding the cosine function and particularly the cosine f function that we used here to calculate our cosine we learned the importance of carefully reading the documentation especially for the arguments that we provide to functions when we call them and finally we learned that sometimes just guessing what we're going to need and going into the documentation doesn't help us so we have to google some reasonable search terms and then filter through the results trying to find what we need and while that might feel frustrating it is also a natural part of programming so reading documentation and searching for answers that aren't immediately obvious in the documentation are both important skills for you to develop in this lecture you got some more practice reading documentation in this lecture you'll learn how to debug in visual studio and even if you're using xcode you should watch this lecture so you can learn a little bit more about the debugging process speaking of the debugging process here's one good way to think about the steps we take when we need to debug our code the first thing that happens is we discover that there's a bug in our code there's a problem with player input there's a problem with the math that we're calculating the projectiles in our game aren't inflicting the kind of damage they should something tells us that something's going wrong in our code the next thing we do is we form a hypothesis about the source of that bug what could be causing the problem that we're observing when we run our code or play our game then we fire up the debugger to see if in fact our hypothesis is correct or we may discover oh that was a bad guess that's not what's causing the problem but let's use the debugger to try to find the actual bug and then finally we fix the bug so that bug is no longer in our code let's go see how this works in visual studio this is the code that we're going to debug and what it's supposed to do is prompt for and get an angle in degrees convert the angle to radians and print out the sine and cosine of the angle when we run the code i'll enter 45 because i know the answer for that and we are clearly getting incorrect results here now we could just examine our code and try to figure out what's going on but let's practice using the debugger my first hypothesis could be that i'm reading in the angle incorrectly so as i look at this code i've declared a variable for the angle and i've prompted for it and i've read it in so let's put a break point here on line 20 so that when we run our code it will stop at line 20 and we can look at the value of the angle variable we set a breakpoint by clicking over here in this gray vertical bar on the left so left clicking in that bar will set a breakpoint left clicking on a breakpoint will remove the breakpoint so i want a breakpoint and this is one of those times where we don't want to use control f5 to run our code because we're actually using the debugger this time so we want to debug start debugging which is just f5 not control f5 when we start debugging the command prompt window opens up it executed the line of code that outputs the prompt i'll enter 45 degrees and hit enter and then we come here and we stop we can tell what line we're on because here we have a yellow arrow on the left that points to this line so we've stopped at this line and i'll turn on the magnifier for us so here on this line of code we can look at the value of angle by doing a variety of different things we can hover over angle and if we do we can see it's 45 so we know we're reading in the angle properly and if we go down to the bottom in the locals panel we can also see that angle has a value of 45 so we in fact read in the angle properly now we're going to convert the angle to radians and you should know that 45 degrees is pi over 4 radians so that should be about three quarters right around 0.75 after we step over this line of code there are a number of ways we can step over a line of code in the debugger you can go up to debug and say step over which is f10 or of course you can press f10 but when we step over it you can see that the yellow arrow moved down to the next executable line it doesn't stop on blank lines it doesn't stop on comments it goes to the very next executable line of code but it did execute line 20 when we stepped over that line if we look at angle now we can see that our angle is 2578 and that is clearly not correct right it should be about 0.75 so using the debugger and testing our hypothesis and then when we discovered our hypothesis was incorrect we were able to step over the next line of code and that actually turned out to be our bug so it's not that we're reading in the wrong angle it's that we're converting the angle to radians incorrectly and by the way down on the bottom you can see that the value of angle changed and visual studio shows us in red that that particular value changed when we executed that line of code i'm going to turn off the magnifier i'm going to stop debugging and we can stop debugging by clicking this red box near the middle top of visual studio and i'll remove this break point assuming i won't need it anymore and if i look at how i'm trying to convert degrees to radians i have this exactly backwards i need to multiply by pi and then divide by 180 not multiply by 180 and divide by pi so let me just fix this and i'll compile again and once you think you've solved the bug there's no need to use the debugger to test that we can just run our code again and if our code gets the correct answer we fixed our bug and if it doesn't then we form a new hypothesis and we use the debugger again and so on so let's go ahead and run the code 45 degrees and i get the correct answer for sine and cosine to recap in this lecture you learned about the debugging process and you learned how to debug code in visual studio in this lecture you'll learn how to debug in xcode and even if you are using xcode you should go watch the video about debugging in visual studio to learn more about the process we follow when we debug our code let's go see how to debug an xcode this is the same code that we just debugged in visual studio except for our javadoc comment up above so i'm going to prompt for and read in an angle and then we're going to convert the angle and print out the cosine and sine i want to set a breakpoint because remember i have a hypothesis that i'm reading in angle incorrectly so i'll just go to the left of the line where i want the breakpoint and i will left click to place the breakpoint there now i can actually just run my code i don't have to run it in a different way like in visual studio we start debugging versus not debugging i can just command r and allow access to my documents folder and now down on the bottom right i can type 45 and then i end up here at this particular line of code and if i hover over angle i see it's 45 and if i look down here in the lower left i can see it's 45 so again i know i am reading in the angle correctly so now i want to step over line 20 so i want to execute line 20 and move to line 23 and i can do that by either clicking debug step over or using f6 and now if i look at angle again we see that it's that horrible 25 78 which is a huge number not around three quarters so i can stop debugging with this black square on the upper left and so i'm not debugging anymore and i don't want this break point hanging around anymore so if i right click it i can delete the breakpoint i can't just click it to delete it that disables it but it doesn't delete it so i want to totally delete it and i'll do that and now i'll fix my code like i did before and i'll command r again to rerun now that i've fixed the problem and i'll enter 45 and i get the correct cosine inside so that's how we can use the debugger in xcode for a console app to recap in this lecture you learned how to debug in xcode in this lesson you'll learn the foundational concepts behind the object-oriented paradigm the big idea is that we can build a software as a set of interacting software entities or objects this is a great paradigm to use for game development because our games are regularly composed of interacting entities in the game world think of players and npcs think of bullets and asteroids you could even think of landmines and teddy bears so what will you learn about in this lesson you'll learn the difference between classes and objects you'll learn that each object has state behavior and identity you'll learn how to construct an object you'll learn how to use getters and setters on an object you'll learn to call the functions that an object exposes for us to use and finally you'll learn how classes and objects work in unreal engine we'll start this lecture by talking about objects and before we talk about the details you should think of objects as software representations of tangible entities or things ships asteroids projectiles entities that we might want to include in our games every object has three things every object has state and state is the characteristics of the object if we're thinking of a ship that ship has a certain amount of fuel it has a certain velocity vector it has a certain angle at which it's rotated there are particular characteristics that that object has and those characteristics are called state every object also has behavior so behavior is something that we can tell an object to do for example we could tell our ship to rotate and sometimes we think of it as something that we can tell an object to do to itself so we can tell our ship to refuel itself or something like that and when we talk about decks of cards later we'll say the deck should shuffle itself so those are behaviors those are things that the object can do we can tell it to do or we can tell it to do to itself the final thing an object has is identity and identity makes it so that we can distinguish this ship from this ship it gives us a way to distinguish between objects in practice the software representation of an object lives at a memory address so different objects are at different memory addresses okay i know we've been talking about a ship but let's talk about a playing card what's the state of a playing card well playing cards have rank ace through king suits and whether or not they're flipped over or face up so we can store the state in good object oriented design in something like c plus plus we store the state in fields and fields are really just variables that are available throughout the class not just in a particular function like we've been using so far or that we've generally been using so far we don't however want people external to the class to be able to just access those fields directly instead we provide them with things that are called getters and setters or accessors and mutators people use those two different pieces of terminology and i will use those two pieces of terminology interchangeably but they allow consumers of the class somebody outside the object to either access state by saying hey what's the rank of this card or by being able to set pieces of the state which we actually won't do in our card example the next thing is behaviors what behaviors does a card have well the most obvious one is that we can flip a card over right if it's face down we can flip it over and now it's face up and behaviors are implemented through functions now i will say that getters and setters are also functions but we tend to think of them as distinct from behavior functions because they're really just designed for accessing the state of the object it's also the case as we can see with this example that calling a flip over function will in fact change the state of our playing card right if it's currently facing if it's currently face up and flipping it over we'll make it face down so functions sort of general behavior functions also are likely to change the state of our object but they're distinct from getters and setters in the way people think about it finally identity so each object that we create from the class and i'll talk about the distinction between classes and objects before we're done but each time we create one of these objects which is called instantiation that object gets a place in memory to live and that gives it its identity here's a conceptual picture of our card class the way well our card object the way we've been thinking about it so at the core that inside part the donut hole although it has stuff in it is the fields that we're going to declare for this particular object so we have a boolean that will tell us whether or not the card is face up and we have its rank in suit and then we have the getters and setters spread around we can get the rank we can get the suit and we can ask is face up so for getters and that's all we have in this particular discussion right if the getter returns a piece of state that's boolean it is general convention to say is instead of get and that actually makes it so that when we build boolean expressions which we'll learn about in the next course in the specialization as we build boolean expressions they'll be more readable and finally we have the one function that is a behavior function the flip over function so this is sort of a picture of a card object there are two important ideas that go along with the object-oriented paradigm the first is called encapsulation so as you can see i now have a magenta boundary around my object encapsulation simply means that we put the data and the operations those getter setters and functions that affect the data all in one software entity so we've encapsulated them inside this shell to make them all together so that's one important object or an idea is encapsulation another really important object oriented idea is information hiding so now as you can see i have shaded all the internals of this particular object and that's because somebody outside the object can only interface with the object through the getter setters and functions and they don't know anything about how the implementation is implemented on the inside right they don't know if we have three fields or 20 fields they don't know the code that is contained in get rank they don't know how the flip over function is actually implemented and this is great this is a huge idea because if we do good object oriented design and we use information hiding then say we have tons of other pieces of code that use my object if i change the guts but i don't change the interface all of those things still work and that's fantastic we for maintainability it makes it so we don't have to worry about changing the internals because everyone interfaces with this object through the interface through that boundary of the object so i told you i would tell you about the difference between classes and objects before the end of this lecture and i've sort of been using those terms interchangeably but there is a precise difference between them so a class defines all the fields and the getters and setters in the functions for any object we create from the class so you can think of this as a cookie cutter we want to make cookies and the class defines sort of the shape conceptually of the cookies now cookies with behaviors might give you nightmares but this is just think of the metaphor as this is the cookie cutter we'll use to make cookies so it defines the shape the fields getter setters and functions for any cookie we make an object is actually the sort of real live instance of the class and you can think of it as the cookies we make with the cookie cutter so we make a number of cookies and then the cookies can interact with the real world and we can well the software world and we can interact with them by you know biting them or whatever we choose to do with our cookies and they'll interact with each other we throw them at each other and they'll break and all kinds of stuff so the objects are the things that we actually put into the real world well okay the game world by instantiating the class that instantiation thing and i will point out that each cookie holds its own state right we can have two ships that this one has a half a tank of fuel and this one is full and they're going in different directions and they're rotated at different angles or we can have two playing cards and they have different ranks and suits that's kind of the only way you can build a card game right is if all the cards aren't the same so when we create an object we are giving it sort of embodiment in the game world and it will now maintain its own state this is actually a more common representation of a class and this is in something called unified modeling language or uml so at the very top we have the class name and then we have a set of fields and in uml we give the name of the field and then the data type that is exactly opposite of the way we declare variables in c plus plus but we're going to use real uml notation when we use uml notation and the name of the field comes first so these are the three fields that we're including in our card class and then at the bottom this says methods and i keep saying functions i will say that people call these behavior implementations in c plus either functions or methods those two terms are interchangeable i will consistently call them functions but visual studio which i use to generate this uml diagram calls them methods but those two words functions and methods mean the same thing and then we list each of those functions that we have the three getters and the flip over behavior function to recap in this lecture you learned some important object oriented ideas you learned that we have object oriented classes that we use to create objects and you learn that those objects are the things that we can actually have interact with each other to actually implement our game world last time we learned some of the conceptual ideas behind classes and objects in this lecture we'll start using classes and objects in a c program the first thing we need to know is how do we construct an object how do we use instantiation to get an instance of an object so that we can interact with that object so that's what we'll learn how to do in this lecture this is our starting point for this lecture so what we're going to do in this lecture is we're going to create a deck object which under the covers uses the deck constructor to create that object and to put it into a variable i need to point out that all this stuff that we're using the dec class and there are actually other things included too like cards and ranks and suits those don't come automatically in c plus these are actually in a dll a dynamic link library that i wrote to include this reusable code so this is more like using a library that somebody else provided but it's not a c plus standard library it's code that i wrote and i integrated into this visual studio project as a dll so you can't just fire up a new console app and type deck and expect it to work because i've done extra work in this visual studio project to include all the stuff we're using today from that dll okay so we want to create a deck object and we need to understand more information about the constructor we need to know in particular if the constructor requires us to provide any arguments to initialize the deck and the way we find that out is by reading documentation and here's the documentation for all the stuff that's in the dll that i included in this particular project how did i get this documentation i did all the javadoc style commenting that i told you we would do in our code throughout the course and then i used a tool called doxygen to generate the documentation from those comments so this is why we do documentation comments so that we can generate documentation for users of the code or consumers of the code that we wrote so over here on the left i'm going to click on classes and here's a class list and i'll click on deck because we're trying to use the deck constructor and i'll even zoom in so that you can see that the public member functions that we have available to us in the deck class are the constructor the constructor is always the same name as the class and then we have an is empty accessor that we'll look at next time and then we have four different functions cut shuffle take top card in print that we'll actually look at not next lesson but the lesson afterwards so what we care about at this point is the constructor and i can click the constructor and it takes me to the constructor and it turns out that there are no arguments that i need to provide when i call the constructor and we know that because there's nothing between these parentheses just looking forward when we cut the deck we're going to have to say where we want to cut it so we're going to have to provide an argument when we call the cut function and that's shown right here and there's discussion about that particular parameter but the constructor doesn't have any of those so we know we can just use the constructor without providing any additional information back in our code our inclination is to come here and say dac for the data type the class name that we're trying to use which is dac and to name our variable and we're going to name our variable dac so this is okay it's okay the compiler can figure out that this is a variable name but it doesn't know about dec the class yet that's why we have red squigglies so we regularly find that we need to pound include header files for classes we want to use so first i'll type the pound include and then we'll talk about header files and we'll explore this much more when we are creating our own classes about how we structure header files and cpp files so all you need to know for now is when we're using a different class if it's not already built into a predefined c plus library like this we need to include the header file that in many ways defines the interface to the class it doesn't have all the implementation details in there but it does have information about the interface into the class so putting the information about the class into files the header file and the cpp file make it so we can distribute the header file with our dll because people need to know how to use the class but we keep all the implementation details inside the cpp file which they don't get when they get the dll so that's information hiding they don't get to see the implementation details okay but we still have red squigglies here on line 14 and the reason is because just as if we type c out which we've used before we get red squigglies but if we provide the name space for c out the red squigglies go away sorry that's such technical terminology so we know dag from our documentation let's go back and take one more look we know that dac is actually in the console card's namespace and i've scrolled up and you can see that up here as well so it's in a namespace that i defined for all the classes that go in the dll we either need to do this which fully specifies the name of this class or as i've shown you before we can say using namespace console cards and while i did say when i was talking about using the standard namespace that i didn't want to do it this way my general rule will be that if i'm using built in c plus plus name spaces i'm going to fully specify them if i'm using name spaces for code that i've written or sort of custom code that's not c plus plus standard code i'm going to include using namespace for that particular namespace because that makes this code easier to read i'm going to run the code even though there's nothing at all interesting to see just to show you that we can in fact run the code and even though it's not obvious what happens here is we're actually calling the deck constructor which i'll tell you actually fills up the deck with 52 cards it's not obvious from the syntax that that's what's happening but that's what's happening it's calling the constructor to create a deck object and put it into this deck variable to recap in this lecture you learned how to use a constructor to construct an object last time we learned how to use a constructor to get an object so that we could interact with that object this lecture will actually interact with that object by accessing its state using a getter and as i mentioned a couple of lectures ago getters and setters are also called accessors and mutators and i will use that terminology interchangeably okay let's go see how to use a getter this is the code that we ended with last time and this time we're going to use the only accessor that the deck class exposes so our first step is to go to the documentation and the is empty function is our accessor and i clicked it so that we could see that it gets whether or not the deck is empty so we've got this description of what the function does we can also see that because there's nothing between those parentheses we don't have to provide any information and that makes sense we don't have to provide any information because we're just asking a question about the internal state of the deck and the deck knows about its internal state so we don't have to tell it anything else when we call this function i'll show two different ways to do this first i'll declare a boolean variable and i'll call it empty status is equal to and here's how we call any of the functions whether they're accessors and mutators or getters and setters or other kinds of functions we use the same syntax every time we put the name of the variable dot and then as you can see intellisense says well here's what you can do once you've put the name of the variable in the dot and is empty is the function we're calling so we can just grab it like that and put the open and close parentheses which we always need when we call a function even if we don't have to provide anything between them we still need those parentheses for the compiler and now i will print out that empty status so when we run our code the first thing that happens is it creates a deck object and puts it into the deck variable then we ask the dac are you empathy and then we print out the results of asking the deck that question and we get an answer that says zero which means false i will say that experienced c and c plus plus programmers can easily do the translation from 1 to true and 0 to false when we're looking at bools but we can also make the output actually print true or false by saying standard c out standard bool alpha so now if i run the code again it actually says false so you can decide to print out ones and zeros for true and false or you can send this bool alpha to the output stream and then your boolean output will be expressed as true and false and that's certainly my preference so i'm going to leave that in the code the other way we can do this though is we can also just say you know i don't need a variable for empty status hanging around i'm just trying to print that out to show that i can use the accessor correctly so we can do this instead we can grab that function call and put it here instead and get rid of our variable declaration completely and now if i control f5 i get the same exact result so i don't have to put the result of an accessor into a variable if i only need it briefly i can just use it in my output or to do whatever else i need to do with it but i wanted to show you both ways of doing this in the code that i give to you i'll add back in that other way we do it i'll have it commented out so that you can see both ways and decide which way you want to do it but this is probably the more common way to use an accessor for a very brief period of time and nowhere else in our program to recap in this lecture you learned how to access the state of an object by using a getter in the previous two lectures we learned how to use a constructor to create an object we could interact with and then we interacted with that object to get access to the state of the object through a getter or an accessor in this lecture we'll access the behavior of the object by calling a variety of different functions we're starting with the code that we had last time and we're going to come down to the bottom of our code and this says call methods but we're really going to call functions some people call the functions in c plus plus methods other people call them functions i think we'll stick with the functions terminology here so looking at the documentation we can see that the deck class exposes four different functions and we'll go through them one by one so that we can call each of them we'll start with the print function and we can see we don't have to provide any information as arguments when we call the print function and it prints the cards in the deck from top to bottom back in our code all we have to do is say dec dot print again using this name of a variable dot name of a function open parenthesis close parenthesis let's go ahead and control f5 and we see that all the cards are face down in the deck so it refuses to print them for us and that makes sense right all the cards in the deck are face down and we can't see their values so this is in fact printing the deck and it's printing each of the cards in the deck it's actually telling each of the cards in the duct to print itself but it's not giving us really good information here but it is giving us accurate information here so you'll find that even though this print function has been provided as part of the deck it's more useful if we walk through all the cards in the deck flipping them over and then print the deck but i did want to show you how we can actually call the function the next function we'll call so that we can actually take a look at how things are happening in the deck is we'll call the take top card function and the take top card function also doesn't require any arguments right you can't say give me the card that's three down from the top in the deck because that is typically considered cheating but we can take the top card and when we take the top card it hands something back to us it gives us a card object from the top of the deck it removes it from the deck but it hands us a card so i'll just comment out this print function because that's not useful to us at this point but i'll leave it in the code so you can see how we did it so we actually can go like this we've got a card i'll call it card zero so there's a card class also in this dll and you can see over here in the headers that there's a card dot h file i'll call it card 0 and i'll say deck take top card and now if we look at the documentation for the card class by looking over here and seeing there's a card class as well we can get the rank of the card we can get the suit of the card we can check to see if the card is face up we can flip the card over and we can print the card so let's start by just saying card zero dot print and see what happens when we control f5 it tells us the card is face down so this is more evidence that when the dac was printing itself it was just telling each card to print itself but each card was face down so each card was saying hey i'm face down we can tell card 0 to flip itself over and now when we run we see that the king of spades the king of spades was on the top of the deck and we took it off the top of the deck we flipped it over and we printed it and we discovered that it was in fact the king of spades now what i'm going to do is i'm going to go back to the deck class and i'm going to call shuffle before i take the top card and again we see we don't provide any information before i do that let's go back to the code for a moment because i want to show you that i can actually also do this this will compile this will run and you should think about what's happening what am i doing i'm taking the top card off the deck and i'm just throwing it away so if i then took the next top card off the deck and flipped it and printed it i get the queen of spades because i took the first card off the deck and threw it away so we actually can call functions that return objects to us or ins or floats or anything that have a return type we can call them without putting the result anywhere and it's just like us saying i don't care about the result i'll just throw it away and you could do this if you wanted to get rid of the top five cards of the deck you can just call take top card five times and not put it anywhere and then start using the deck from there so that's valid syntax and it's even valid in i'm going to say rare cases but almost always if a function returns a value you should use that value somehow either print it out right away or store it in a variable to use later or something like that okay let's go to shuffling the deck again i'll comment this out i'm trying to space this out so that if you look at the code later it makes some sense to you about the structure of the code so let's shuffle the deck and while we won't have strong evidence that the deck actually got shuffled because we can't look at the ordering of the cards with all of the cards face down we can at least make sure that we're not getting the king of spades off the top of the deck so i've shuffled the deck and now i'm taking the top card and i got the queen of clubs okay the last function we have in the deck class is cut and cutting the deck we do in fact need to provide an unsigned int for the location at which we want to cut the deck this is not just an int because ins have negative numbers so saying we want to cut the deck at the negative eighth card that makes no sense at all so when i wrote this function i said the parameter on the function side and the argument on the calling side needs to be an unsigned in so it starts at zero and is always positive let's go call this function so let's go ahead and cut the deck and first i will show you that i can cut the deck after the zeroth card programmers start counting at zero for very good reasons that i'll talk about later in the specialization but i'm going to cut the deck at the zeroth card which means i'm going to cut it just past the king of spades we know the king of the spades is on the top of the deck if we haven't shuffled it when it's created so i'm going to cut the deck taking the king of spades off the top of the deck and putting it on the bottom of the deck so cutting the deck just past card zero should give us the queen of spades and it does as expected i could cut the deck just after the 13th card in the deck because we're doing zero based counting and i should get the king of some other suit because i know when i built the deck my first 13 cards were the king through the ace of spades and i know that because i wrote the class you don't know that as a consumer of the class i know that because i wrote the class and so i see the king of hearts and i could even figure out what order they go so spades hearts diamonds and we could just clubs right we should have known that even before we did it so the last function here it doesn't return anything because it's just changing the internal state of the deck but we do provide information to tell it where we want it to cut the deck to recap in this lecture we accessed the behavior of an object by calling a variety of functions and we used the documentation to make sure that we were calling those functions properly this will be an incredibly short lecture but i wanted to keep the unreal engine discussion distinct from the pure c plus discussion of classes and objects so in unreal the scripts that we create are in general classes and when we drag one of those scripts to make it an actor in an unreal map that is an instance of the class or an object it turns out that we won't use constructors to create objects in unreal but we'll explore the details of that in the next module so to recap our scripts in unreal are almost always classes and when we pull one of those scripts into the map as an actor that's an instance of the class or an object what will you learn about in this lesson you'll learn how the unreal editor is arranged you'll learn about meshes and actors in other words when we import a model into unreal and then add it to our map in the lights camera lecture you'll learn how to set up an orthographic camera and a light to light our models properly so throughout the courses in the specialization we'll be importing 3d models but all our games will keep everything in the yz plane so essentially we're building 2d games using 3d models you'll remind yourself or i'll help remind you that scripts are actors and then we'll look at how we can debug a script in unreal we'll look at blueprints which are reusable assets we'll study basic physics and we'll learn how collisions work in unreal both collision detection and collision resolution in this lecture we'll explore the different parts of the unreal editor so let's go do that this is the default layout for the unreal editor and throughout the courses in the specialization i will just use the default layout so there are a number of different areas that we need to know about when we're using the unreal editor first at the very top here is a menu bar so you can do sort of the standard things in the menu bar and periodically i'll show you how we use the menu bar to do some of those standard things over here on the left is what's called the modes panel and we'll most commonly use the modes panel to drag assets from there into the map and the map which you can also think of as a level is displayed here in the viewport panel which you'll hear me and many others simply just call the viewport so one of the ways that we add assets to our map is to take the mode panel and drag them over and drop them into our map another way that we add assets to our map is down here on the bottom using what's called the content browser and this not surprisingly lets us browse our content and you'll see as we develop our unreal games throughout the courses in the specialization that we will populate this content browser with assets that we can then drag into the map and by the way when we drag an asset into the map it's called an actor so it's an asset when it's just sitting off somewhere in a folder but once we drag it into our map it's an actor over here on the upper right you can see the world outliner so this shows everything that's been placed in the world and these are default assets that are placed in our level this is with no starter content this is just the basic stuff that unreal adds to a no starter content project so you can see if i select floor for example i've now got the floor selected in the map itself and you may have noticed that a whole bunch of stuff showed up down here so down here is called the details panel and the details panel is where we modify characteristics of the actors that we have in our map so for example if i decided that i wanted the floor at 100 z instead of 20 i can just do that and i've just moved the floor up you'll also commonly see as you move things around this message that says the lighting needs to be rebuilt and there are a number of different ways we can build the lighting we can control shift semicolon and if you do that it says it's starting up a swarm connection that's just the lighting builder in unreal you'll see some messages down on the lower right and then lighting has been rebuilt the other way you can rebuild lighting is by using this toolbar that you see along the top above the viewport so you can also click this down arrow and you can say build lighting only so that's another way to build lighting if you've forgotten the hotkeys for building lighting and of course this toolbar also gives us other options like saving current which can also do with control s it lets us play the level which isn't exciting with the default level and a variety of other things that we'll explore as we build games the only other thing that i'll talk about in this lecture because we'll be interacting with all these different parts of the editor as we build games this is just a quick tour of how that works is down here on the bottom you'll see i also have an output log tag and that doesn't come by default but we're going to use that a lot especially early on in the first courses to display messages so if you don't see the output log tab in your configuration you can always go to window developer tools output log and select output log and that will give you the output log panel and you can drag it down over here and dock it next to the content browser and so on this is a pretty standard interface where you've got dockable panels and you can peel them off from where they currently are and move them somewhere else but i'm going to just leave it as the default layout so that we don't have to worry about that changing the way it looks if you keep the default layout as well then your unreal editor will look the same as mine and that will make it a little easier to follow along as i'm doing things and that's a quick tour of the unreal editor to recap in this lecture we learned that the unreal editor has lots of panels that are useful to us as we develop unreal games in this lecture you'll learn how to import models into unreal and how to add meshes to your unreal map a model is a graphical 3d asset and when we import a model into unreal we get a mesh and one or more materials and one or more textures an actor is an entity that we've actually placed in an unreal map let's go see how all that works i've created a new unreal project called meshes and actors and our goal here is to get a model imported into our project and drag it into the map the first thing i'm going to do is i'm going to come over here in the content browser and i'm going to add a folder here in the content browser so i right clicked and i'm selecting new folder and i'm going to call this folder meshes and actors the reason i'm doing that is because we're going to try to follow this unreal engine style guide as much as possible for the naming conventions in our unreal engine projects and those naming conventions apply to folders and folder names and folder structure as well as the asset names for the assets that we import or create in our unreal engine games and there's the url magnified so that you can read it and easily type it in and bookmark it in case you ever wonder how you should name assets as you're developing unreal engine games this is really a great style guide so we're going to try to follow this as much as possible now that i have my meshes in actors folder i'll double click it and i'll create another folder called maps so i can store all the maps in my game in a single folder and i'll save this map into my new maps folder and i'm going to call it map zero as we build more complicated games we'll certainly call our maps gameplay and perhaps main menu or controls menu or those kinds of things but for now we can just call it map it would be convenient if this map opened up in the editor whenever we opened the editor it's not currently configured that way though so let's fix that by going to edit project settings and on the left i'm selecting maps and modes and i'm going to change each of these to be map zero and that will make it when we start up the editor it goes to this map and when we start up the game it goes to this map and so on i'll also go to the project description and say if you want to avoid the annoying comment that says this at the top of each of the scripts that you create you can change that here and that will populate that top comment on your scripts with whatever you've put here instead but since i'm not adding any scripts in this particular project i'm not going to bother doing that once we're done here in the project settings we can just click the x in the upper right hand corner and close that panel just as you'd expect okay the art assets should go into a folder called art and when i double click art i'm only going to import one fbx model into this particular game just to show you how that process works but generally you have multiple models in your game and typically i will create a folder for each of those models that i'm importing so i'm going to right click here and i'm going to select import to game meshes and actors art dot dot and here's where i'm going to import my model so i'm going to navigate to an fbx and select that using this browser panel and once i've selected that we'll come back and continue with the process so i've selected a static mesh called sm yellow teddy bear that's the fbx file name right there and i'm going to leave everything here as defaults i will say that this is a static mesh it's not something called a skeletal or skeletal mesh which would mean that i'd want to check this checkbox here but the skeletal mesh is actually it's got bones and it's skinned and it's rigged to do animations and we're not going to be using any of those kinds of models in this specialization we're focusing on the basics of c plus plus and c plus plus in unreal engine doing interesting things we're not focusing on the more complicated 3d things we can do like animating meshes we'll leave that for your future exploration so i'm importing a static mesh i'm leaving all the defaults and i'm saying import all i'm going to turn on the magnifier and down here in my content browser i end up with a number of different components of the static mesh i have the mesh itself right here i have a material for the mesh right here i have a diffuse or specular texture for the mesh so it's color and so on and i have a texture that specifies a normal map for the mesh so i made a big deal about following the naming conventions at that website but the name of this static mesh for example the base asset name shouldn't be in snake case here it should be in pascal case that's an easy fix for me i'm going to right click and rename it and now i can just make the name have the base asset name and pascal case instead you certainly can have your artist change this as well but i wasn't very specific for my artist about how exactly i wanted everything named so some of these are pretty close it turns out that we want static meshes to start with sm we want textures to start with t we want materials to start with m and so on so i sure do some of that with him but i didn't actually say the exact name i wanted to use for these assets in the game so i could certainly have had him go back and rename everything in maya to export so i didn't have to rename here but it's certainly reasonable for me to just rename them here as well so i'm just going to rename all of them i will also point out if you didn't actually have to rename them you still want to save them these two assets have stars which mean they haven't been saved as you assets yet unreal assets so if you don't have to rename them you can just select save all and click save selected and it will then save them in the unreal asset format but i'm going to rename them renaming them automatically saves them as well when you're done renaming but i'm going to rename these so that everything is the way i want it to be for my asset names in my game just one more to go and i'm going to turn off the magnifier now so as i said in the previous lecture when we take an asset and we drag it into the map we have turned that asset into an actor in our map and for all the games in all the courses in the specialization we're just going to set x to be 0 and we're going to play our games in the y z plane so y goes to the right here that's that green arrow and z goes up that's the blue arrow so now we've added our static mesh into the game and as you can see in the world outliner panel it's got a name and we can rename it here if we'd like to we can change it to moving if we were going to move it around and if i click on the actor here in the world outliner panel then it focuses me right in on my actor i think i'd like to actually make y b0 and zb0 and by the way you can navigate around the world with your mouse and i'm going to let you just explore those different ways to do it it's not worth me just saying well sometimes you alt left click and so on just experiment with that to navigate around the world i am going to get rid of the floor so i've just selected it in the world outliner and hit the delete key and if i play the game right now sadly i can't actually see the teddy bear in the game that's okay and the next lecture we'll see how we can add an orthographic camera and change our lighting source so that we can actually see the teddy bear in the game so the focus on this particular lecture was how do we actually import the static mesh into our project to recap in this lecture you learned that a model is a graphical 3d asset you've learned that when you import a model into unreal that you get a mesh one or more materials and one or more textures and you also learned that an actor is something that we've placed in an unreal map in this lecture you'll learn how to set up an orthographic camera and a light source so we can build 2d games our games are actually 3d actors in 3d world but we're going to treat them as 2d games by keeping all our actors in the yz plane let's go see how to add our camera and set up our light source this is where we ended up in the previous lecture i have a teddy bear mesh static mesh in my map but we can't see it when we run the game and because all the games that we're going to develop in the courses in the specialization are essentially going to be 2d games we're going to keep all of our actors in the yz plane so at x equals 0 and that means that an orthographic camera is a better choice for the games we're going to develop let's add an orthographic camera to the map i'm going to come over to the modes panel and it turns out that we can search for the things we want to add and i'm going to add a camera to the map and i'm actually going to add it at 500 in x and 0 in y and 0 in z i'm also going to say that the camera is static i'm not going to move it around as i play my game i'm going to make it orthographic and i'm going to leave these settings the way they are so i'm going to make sure my camera actor is selected and then i'm going to come up here and select blueprints open level blueprint and while we're in a c plus unreal engine project we're going to use the blueprint scripting language just to set up the camera in the level we could actually do this by writing a separate c plus plus script and so on but there's no need for us to do that we can just use blueprints just for this one thing so don't worry about the details of how is this scripting language working and how are functions getting called and so on these are just the few basic steps we need to set up our orthographic camera i'm right clicking here and i'm going to search on player and i need to get the player controller so i've clicked on that and then i drag off the return value and i say set view target with blend and then i connect those two together i will point out that that begin play event is the same as the begin play function that we used in our script to send a message to the log we're almost done here all i have to do is right click and create a reference to the camera actor and make the camera actor the new view target i'll move this out of the way and that's really all we need to do to set up our orthographic camera i'm going to compile because this is code it's just in a visual scripting language and then i'm going to save because it compiled find and i'll close that panel the other thing that i want to do before i move the light source around is i want to get rid of the actors in the map that i don't need i need the atmospheric fog to give us a background i need the camera actor to render the map in an orthographic way i'm going to need the light source to light my model i don't need player start we'll need it again later in the courses in the specialization not in this one but in later courses but we don't need it for now we don't need the sky sphere we don't need the skylight let's keep our teddy bear model but we don't need this either so at this point i'm going to change the characteristics of my light and remember this is the default light source that was added to the map by unreal i'm going to change x to negative 500 because i want to light the model from the front i'm going to set y to 0 but i'm going to set z to 100 so that it's above the camera and then for rotation i'm going to use 0 in x negative 10 in y and 10 in z and when we run we still can't see it because i made a mistake so our camera actor should be at x equal negative 500. you can see the teddy bear there in the preview and my light source is in fact already at negative 500 so now when i play we got this weird sphere sometimes that happens i'm going to play again and there you can see my teddy bear in the middle of the screen now that teddy bear is pretty brightly lit so let's fix that we'll take the light source and we can change the intensity here and i'm actually going to change it to be really really mild so 0.2 lux when i run my game again as you can see i now have my teddy bear in the background it's got this nice blue background behind it and it's an orthographic view so we've set up both the light source and the camera actor to give us an orthographic view with a good location for the light and a good intensity for light for really all the models that we're going to use in the courses in the specialization and of course i should save my map and that's it for our unreal engine work for this lecture to recap in this lecture you learned how to set up an orthographic camera so we can treat our games as 2d and you also saw how we could set up a light source to render our meshes properly as we've done in several previous lessons we can create c plus scripts to implement custom behavior we've always selected actor as the base class for those scripts when we create them and when we drag those scripts into the map we've been turning them into actors this lecture is a reminder of how all that works i've created a new project and set up folders and saved the map i haven't bothered with the orthographic camera or the light because in this lecture we're just reminding ourselves that scripts are actually actors in our map i'm going to come up to the top menu bar and say file new c plus class i will select actor i'm going to change the name of my script to say hi and i'll create the class and then we wait patiently while the code is added to the project and here we are over in the code we'll do the usual stuff i'll say i don't need the tick function to be called every frame but in begin play i want to say hi and remember we use ue log for that we can use the log temp warning the text macro don't forget the semicolon all the way at the end and i'm going to say hi so i'll say hi i'll compile and i need to make sure i do that so that my changes take effect when i go back to the editor and add this script as an actor to the map and run the game so back here i need to navigate to my script so i can drag it into the map to make it an actor and i'll click this folder and i'll expand c plus classes and here i am so i'll just drag it over into the map and i'll select the output log tab and when i play we see that high message i know you've seen this before and i just wanted to remind you that scripts are in fact actors if we drag them into the map and that's important because we'll see in a few lectures how we can take that script actor and turn it into a reusable asset that we can place numerous times into the game or even spawn as the game plays though we won't get to that until the next course in the specialization so i'll save my map and we're all done in the unreal editor for this lecture to recap in this lecture you were reminded that our unreal scripts are specialized forms of actors that implement custom behavior in this lecture you'll learn how to debug an unreal script using visual studio recall that in a previous lesson we talked about the debugging process we'll use that same debugging process when we debug an unreal script i've created a project that has an actor called buggy trigonometry so let's go take a look at that actor i've added our buggy trigonometry code to the script except that we're not prompting for and getting an angle because we haven't learned how to do that yet in unreal so i've declared an angle variable and set it to 45 degrees i'm trying to convert the angle to radians here but m pi gives us a compilation error so let's find out in the unreal engine documentation what we should do instead here in the documentation i'll search on pi and i get a number of results so let's click on this get pi thing because that seems like it might be useful unfortunately this is the blueprint forget pi but it says the target is the kismet math library so let's search the kismet math library and if we click on the top result we see that there's a math library that has lots of functions available to us so let's look for get pie and luckily this is in alphabetical order so we've found get pi we can click on it to see that it returns the value of pi as a float so we can call this function in the u kismet math library to get pi so we'll say i'll steal some code from down below so remember when we fully specify a namespace ukismetmathlibrary is a namespace so we put the namespace colon colon and then we can call getpie to actually get pi now one of the important things in that documentation was at the very top of the documentation and it said we need to include the kismet slash kismet math library dot h header file so i've already done that here in the script i already knew i needed to do that so i did it here so we're using the ukis math library namespace which is specified in the kismetmathlibrary.h header file so we have to pound include that header file so that we can use stuff in that namespace i made a mistake here i wanted us to have a bug so let's add our bug back in and i meant this to be the buggy code from before and as you can see when i run it we get incorrect cosine and sine values in our output log panel so now it's time to actually debug our code now there's lots of information on the internet about how you can debug your c plus plus code with unreal engine and visual studio unfortunately my personal experience has been that sometimes those things work and sometimes they don't and i'll even do something and it'll work the first time and then it won't work the second time so debugging in visual studio with the unreal engine is a hit or miss proposition much of the time i will say that you can always use the ue log macro to print out intermediate values of variables to see what they are as you run your game but i'm a huge fan of using an actual debugger to do stuff so i may have found something that consistently works and i'll walk you through what that thing is so i'm going to actually close down the unreal editor and i went to the folder that holds the unreal project and double clicked the solution file the visual studio solution file the extension for that file is sln and it's the same solution file you would double click if you were doing a console app except of course this is in an unreal engine game once visual studio opens you need to make sure that up here under the solution configurations you select development editor and then you need to rebuild your solution so you select build and you say rebuild solution i've already done that that takes a long time so i'm not going to do it again during the video but now i can set a breakpoint and i can just press f5 to debug just like we did in a console app and what's going to happen here is it's going to actually open up the unreal engine editor and we'll be able to run our game with the visual studio solution attached to that unreal engine game so that we can debug i'm going to turn off the magnifier again and now when i run my game i stop at that break point and i can look at the value of the angle either here or down here and i can see that the value of the angle is horribly incorrect i will point out that i added a little extra to my code to make this work though so compilers will optimize code and optimizing code means that it makes it run more efficiently by sort of restructuring sometimes as it generates the machine code that's going to run on the machine the problem is that in the debugger sometimes that optimization makes it so we can't actually look at the values of variables so for example i might try to hover over angle and if the compiler has optimized that variable away just because it's used temporarily here in this function then i won't get anything when i hover over it and i won't be able to look down below to see it and in fact even the thing down here in locals that says this that i can expand and and look at characteristics of it that also will say this has been optimized away and that's not helpful to us while we debug it's hugely helpful to us as we run our game because we want our code to run as quickly as possible but if we can't look at it with the debugger while we're trying to fix bugs that's not helpful to us so i've added what's called pragmas and this pragma i might as well stop debugging for now and this pragma optimize i'm basically saying turn off optimization for everything there are various levels of optimization and by providing this empty string i'm saying turn off all the optimization so i turn off optimization before the function that i'm trying to debug and then i turn it back on after the function i'm trying to debug so this is a function level command if you will to the compiler and this is a visual studio compiler command other compilers will have potentially different commands for turning optimization on and off so i needed to do that so i could actually look at the value of the angle variable while i was debugging we know that this is backwards so i will multiply by pi and then divide by 180 and i'm going to debug again and i'll just press f5 and i'll run the game again i hit the break point again but this time angle is the correct angle remember about three quarters so now that i believe that i've fixed the problem i can get rid of the break point and i can close the visual studio solution and i've opened the project in the usual way and now when i alt p to run the game we see that the cosine and sine values are now correct to recap in this lecture you learned how to debug an unreal script in visual studio recognizing that it may be easier to just use ue log to output the values of selected variables in your code the process i showed here does not work in xcode so to debug an xcode unreal script you're really going to just have to use ue log to print out those variable values in this lecture you'll learn about how to create blueprints and i'm not talking about the blueprints visual scripting language in unreal i'm talking about something else so what are blueprints they're prefabricated entities in other words they're entities that we've configured to behave the way we want them to and then we've saved them as a blueprint what are they good for in the editor they're useful for adding multiple instances of that blueprint to the map and as we'll learn later in the specialization they're also really useful because we can spawn blueprints from a script i've already built my project i've put the orthographic camera in and set up the light source i've imported the yellow teddy bear static mesh in its material and textures and i've created a script called teddy bear that logs the message saying hi i'm ted i added that script to the map so if we run the game and go over to the output log we see it says hi i'm dead now what we want to do is we want to turn this script into a blueprint a reusable asset that has both behavior printing out a message and a visual representation the static mesh for the yellow teddy bear i'm going to remove the script from the map before i actually create the blueprint i want to put a folder in my content that holds blueprints so i'll go to our blueprints folder i know that's the name of the project as well i already have an art folder that holds the mesh assets i have a maps folder that holds our single map and i'll create a new folder that holds all our blueprints the one blueprint we're going to create now i'll go back to the script and i'll right click the script and i'll say create blueprint class based on teddy bear what that does is it brings up this dialogue for me to name my blueprint and i'm going to always put bp underscore for blueprint underscore for this blueprint asset and i'm going to make sure i put it in that new blueprints folder that i just created once i click that green button i get the blueprint editor panel here and the blueprint already includes the script because we said we were creating the blueprint from the script but it doesn't have the yellow teddy bear static mesh yet so we can come over here notice that i have the blueprint editor not maximized and moved out of the way so i can navigate over here in the content browser and i will drag my static mesh here onto this sphere the default scene route and as you can see at this point i now have both the sphere and the teddy bear but i can get rid of the sphere by dragging the teddy bear up one more time and now i just have the teddy bear in the script built together into my blueprint i'll compile it just like we needed to compile the level blueprint when we set up the orthographic camera and i'll save it and i'll close this so if we go to that blueprints folder we now have this blueprint and if i place one in the scene and make sure he's at zero in the x when i run my game i can see in the output log that he printed that warning i'll also say that i can drag multiple instances of this reusable object into my map making sure that i have them visible and making sure that they're in the yz plane and if i run my game again we can see all three of them and we can see in the output log that they all printed the message one of the things that's really nice about these blueprints is not just the convenience of being able to drag multiple instances of the blueprint into our map i can go back to visual studio and i can change the message in the script and recompile it both to make sure i didn't make any mistakes and to make sure it has an effect when i run the game and then back in the game if i run the game again you can see that all three of those instances of the blueprint are outputting the new message so if we set up these blueprints as reusable assets and we decide to make a change to the behavior of the blueprint then that change automatically takes effect in every instance of the blueprint that's in the map and of course every new instance of the blueprint that we bring into the map later to recap in this lecture you learned about blueprints and you learned how to make one you learned that they're useful for adding multiple instances of the same blueprint to a map and i told you that later in the specialization we'll also discover that blueprints are great when we want to spawn those blueprints into our game in this lecture you'll start learning how to use the built-in physics in unreal and unreal uses the physics phsy software development kit or sdk from nvidia to implement its physics this is essentially what we ended up with at the end of our blueprints lecture i have a blueprint this time for a yellow teddy bear because i have teddy bears of multiple colors and if i all pee he just sits there so in this lecture we're going to implement basic physics we'll come over here to edit project settings and we will scroll down under the engine section down to physics and select physics i'm going to turn on the magnifier so here under simulation we have default degrees of freedom and it defaults to full 3d but remember we're trying to keep our actors in the yz plane so instead of using full d we'll say constrain all our actors to the yz plane so no matter what forces are applied to our actors they won't come out of the yz plane and that's a good thing next if we scroll down to constants you can see the default gravity is in the z direction which is just what we want because z is pointing up in our games and it's negative 980 and that works just fine you should know that the gravitational constant on earth is pretty consistently negative 9.8 meters per second squared no matter where you're located it varies a little bit but that's a reasonable constant to use so we've only changed one setting here but we looked at the gravitational constant we'll close our project settings but it doesn't matter that we constrained our actors to the yz plane still when we run the game the teddy bear doesn't do anything however if we select the teddy bear blueprint and it's sometimes the case that we actually need to expand this area a little bit under components but we want to select the static mesh component on the yellow teddy bear blueprint and if we scroll down a little bit we can say simulate physics the other thing that we'll do is we'll say we don't want any linear damping so linear damping means as we move we slow down a little bit over time and we're not going to have any of that in our game so we'll change that to zero and now when we run our game watch closely the teddy bear falls out of the screen it's important to realize though if i come over here and i drag another instance of the blueprint over here and so up here in the world outliner you can see this is yellow teddy bear 2 and i change the location of yellow teddy bear 2 to be 0 i'm going to move him over a little negative 100 like so when we run our game only one teddy bear falls so this is an important thing to recognize you might forget this once or twice or a hundred times but the changes we made to this instance of the blueprint were just to the instance of the blueprint it doesn't change the blueprint itself we can change the blueprint itself by clicking this blue button that says edit blueprint and saying apply instance changes to blueprint so we're trying to make the blueprint match what we now have in the instance and it did update it but you can see on the blueprint that it now needs to be saved so we'll save it and now if i drag another instance over and make sure it's in a reasonable location if i alt p they both fall down so that's an important step when you're modifying a blueprint in the map you need to make sure that you apply those changes to the blueprint and then save the blueprint to make sure those changes take effect okay i'm going to get rid of this yellow teddy bear too now for this lecture i've also imported a green teddy bear model and a purple teddy bear model and i'd like to have all three of them as blueprints that i could place in the map so i'm going to go to the yellow teddy bear blueprint and i'll right click it and i'll say duplicate and i'm going to change its name to green teddy bear now this green teddy bear blueprint still has the yellow teddy bear static mesh on it so if i double click it to open up the blueprint editor you'll notice it actually brings me to what's called the event graph panel which is not what i really want here the editor thinks i want to start using the blueprint scripting language to edit my blueprint but i don't but i can get back to the viewport that we saw the first time we edited blueprint by clicking the viewport pane and as you can see i have a yellow teddy bear there i'm going to navigate in my content to my green teddy bear static mesh and i'll drag it up and drop it on top of the yellow teddy bear mesh now that is a weird looking teddy bear and i like it a lot but i'm going to make the green teddy bear just be a green teddy bear and i can do that by either dragging this up like we did when we were getting rid of the default scene root or in this particular case i can actually delete the yellow teddy bear and the green teddy bear becomes the new root for the mesh i'll compile i'll save and i'll navigate to my blueprints folder and i'll put one of these in the scene and run my game and it's important to note that even though it brought the behavior over i didn't show you that there's two high i'm ted's one for yellow one for green but it did bring over the behavior of the mash so the physics characteristics that we used on this blueprint were associated with the mesh that's attached to that blueprint when we replaced the mesh we got rid of all those characteristics i'll show you another way that we can edit the underlying blueprint so remember for the yellow teddy bear i did this by changing the instance and then applying those changes to the blueprint i can also open up the blueprint editor i don't actually have to go to the viewport for this but i like to have that view if i select the mesh i can just over here in the blueprint itself i can say simulate physics and set linear damping to zero we'll compile again we'll save again and now when i run my game they both fall down so there are two ways that i can put a change into a blueprint i can edit an instance in the map and then push those changes into the blueprint or i can open up the blueprint editor and make those changes directly there i'm going to do this one more time because i want a purple teddy bear as well i'll open it up in the blueprint editor i'll navigate to my art i'll drag the static model up here and then delete the yellow teddy bear mesh we'll look in the viewport and see we do in fact have a purple teddy bear there i'm going to remember to make this blueprint obey physics more accurately this static mesh that's a component of the blueprint obey physics i'll compile i'll save we'll put one in the game and i'm not sure how i managed to do this but i lost my yellow teddy bear blueprint so let's get him back in there as well and now we've got a yellow a green and a purple teddy bear in the game and when i run they all fall out of the game that certainly basic physics right gravity is basic physics and i did want to show you how those physics settings can be handled or need to be handled as we modify the blueprint by changing the static mesh that's a component of the blueprint to recap in this lecture you learned that the physics sdk in unreal lets us implement physics behavior without having to actually code our own physics simulation and i'll tell you that we can also take advantage of the physics engine functionality from within scripts and if you want to explore that you should do exercises 12 and 13 that let you do exactly that in this lecture we'll learn about collision detection and resolution and we'll learn how collisions and physical materials help us with that in unreal so what's collision detection you won't be surprised to hear it's detecting a collision between two actors in a map if both of those actors have a collision a collidable volume for that actor then the physics engine can detect those collisions automatically and i know that terminology is a little difficult because the collidable volume is called a collision and the collision tube between two actors is called a collision but we'll just deal with that unreal terminology a collision is a collidable volume for an actor what's collision resolution it's doing something as a result of the collision so physical materials help the physics engine determine how the collision should be resolved from a physical perspective and we'll learn later in the specialization that we can also do our own custom collision resolution from within scripts let's go see how all that works if we navigate to our static mesh for the yellow teddy bear and double click it to open up the mesh editor we can actually look at the collision that was added when we imported the model i'm coming up here to the toolbar on the top and expanding this and showing simple collision and then i'm zooming in and you can see that we have a collision volume or what in unreal engine is just called a collision already associated with this mesh if you don't like that particular collision you can come up to collision on the top menu bar and you can remove the collision that was added when we imported the mesh but i'm not going to do that but if you want to you can remove that and then you can add a different collision to this particular mesh and you can add a sphere which looks like a sphere you can add a capsule which looks like a capsule and you can add a box so sphere capsule and box are pretty efficient collisions you can add other types of collisions as well but i'm just going to use the default collision that we got when we imported the mesh i need to add a floor for the teddy bears to bounce off so i'm going to get rid of this from when i added the camera to the scene and i'm going to drag a cube over into the game i'm going to need to manipulate the cube to make it like a floor and so i'll center it in zero nny and i'll put it at negative 149 which through trial and error i have determined is a good place when we display it with the orthographic camera i also need to scale it in y to make it extend the full width of the scene and i'll also make it thinner because i don't need that much there you'll see i have a message that said lighting needs to be rebuilt so i'll do that and now when i run the game the teddy bears fall down and land on the floor now i'd like the teddy bears to bounce more than that so i'm going to add something called a physics material to each of the blueprints that i'm using for these teddy bears these are the blueprints that we had from the previous lecture when we did some basic physics so i'm going to go to content and go into my collisions folder and i'm going to add another folder called physics i'll go into the physics folder i'll right click and i'll say physics physical material i'll select physical material as the class i want to use and click the green button and i'm going to rename this physics material pm underscore teddy bear if i double click it i can edit the physics material and the two things that we're going to care about are friction and restitution so friction is just as you'd expect sort of how sticky it is when you try to slide along it we're just going to leave friction just as it is but restitution is bounciness and i would prefer a rubber teddy bear compared to a 0.3 bouncy teddy bear i guess so the scale of all these values are zero to one so i'll make the teddy bear as bouncy as possible by setting this to one and i'll save it and close this while i'm here i know from past experience that i want the floor to be a little bouncy also so i'll create another physical material for the floor and i'm going to call this one pm floor and i'm going to leave the friction the same i'm going to make it kind of bouncy but not totally bouncy because i know that i get too much bounciness but this is the kind of thing that you sort of play around with and figure out what works best for your game okay i'll save this and now i need to attach the physical materials to each of the actors that i want them attached to for the floor which i have selected here and in fact why don't i just come up here and change its name from cube to floor [Music] that's a little more descriptive and i can scroll down in the floor and under collision i can override this is hard to read because it's cut off a little it's material override and i'm going to pack pm floor as the physical material to use for the floor for the teddy bears it will be easiest for me to modify each of the blueprints rather than modifying these actors that are already in the map so i'll go to content my blueprints folder and i'll double click each one select the static mesh scroll down over here and under collision i'll select teddy bear i'll compile because i changed the blueprint and i'll save and i'll do that for the other two as well so select mesh scroll down to collision and pick teddy bear compile save and now when we run the game we've made our teddy bears really bouncy as bouncy as possible and we've made our floor pretty bouncy not the maximum and we can see what happens and that's pretty good you could just watch that and be hypnotized but i'm going to stop it the other thing that we want to have happen is we want teddy bears to actually bounce off each other as well and i'm going to show that that's happening by adding another teddy bear to the scene pretty much right below the yellow teddy bear that's right there i'll slide it over a little and over here on the right i need to make sure it's at zero and then i'll slide it over and now these two teddy bears will bounce off of each other as you can see and they bounce on top of each other and they fall over and all kinds of great stuff that was a nice little flip now something that you haven't seen is this game running with 18 teddy bears six of each color so i'm gonna go add them and then we'll come back so you can see that okay so i've made it so i have six teddy bears of each color when i run the game now you'll see they bounce off each other and we've lost some of them out of the game which is sad for me so let's make one more change i'm going to add walls on the two sides so i can drag in another cube i can change its name to right wall and i can place and scale it properly so i've placed it on the right hand side and i'll make it skinny and i'll make it tall enough and again i messed around with those different settings to place the wall in the right place and one more cube over here at zero negative two sixty one 0 and again scaling it as 0.1 2.88 and i haven't added any physical material to these but i do need to rebuild the lighting so the teddy bears that bounce off the wall will bounce off them a little bit not a lot like the bounciness from the floor so one more time we'll play the game and the teddy bears bounce around for a while and then stop but we still have all 18. to recap in this lecture you learned how collisions those collidable volumes help the physics engine perform collision detection we saw how physical materials help the physics engine determine how to resolve those collisions from a physics perspective and i also told you though i didn't show you that later in the specialization we can also do custom collision resolution from within our scripts okay you made it to the end of the course great job i know for some of you it might have been a struggle with the programming in c plus that's why i require that you have learned some other programming language first because pretty much nobody does c plus as a first language some of you may have also struggled with the unreal engine unreal engine is a huge commercial quality industrial strength game engine so that means there's a lot of complexity associated with doing even what feels like simple things that's okay though because we've been building up your foundational knowledge in unreal engine there's still tons to learn about using c plus plus an unreal engine so if you'd like to learn that stuff in a structured environment you should move on to the next course in the specialization but if what you've learned has been enough for you to say well i want to start messing around with it on my own to work on games then you should do that too and you should always do that because building cool games is our end goal as we go through the courses in the specialization i want to thank you for taking this course i love doing courses on coursera to share what i know about game development with all of you so i appreciate you joining me on this journey of exploration in this first course cheers hi i'm tim dr t chamelard and i'll be your instructor in this course i'm an associate professor in the computer science department at the university of colorado at colorado springs where i predominantly teach gaming design and development courses but i also teach some computer science courses i'm also the program director of our bachelor of innovation in game design and development i have five and a half years of indie game development experience in a company that i formed with my two sons and now i have a one man indie game dev company called burning teddy this is a four week course and you'll have three programming assignments to complete in weeks one three and four and each of those programming assignments is worth 25 percent of your course grade you will also have a quiz to complete in week two and that quiz is worth 25 of your course grade i've provided you with lots of exercises that aren't worth any points toward your course grade but are really good practice for you to engage with the course material so i strongly encourage you to do that speaking of the course material in this course we'll cover selection which is the way we make decisions in our code we'll cover unreal input so you can finally have the player interact with your unreal games we'll cover iteration which lots of people call looping because it lets us loop or repeat or iterate over blocks of code in our programs and finally we'll cover arrays and containers which let us store multiple values in single variables this course builds on the foundation of c plus plus and unreal knowledge that we started developing in the previous course so i expect you to have a firm grasp of that material a couple of the lessons include chapters from a book that i may or may not ever publish about c plus plus in the unreal engine but that provides you with an additional reference as well and of course if you run into trouble you can also get help from the web or from the course forums let's go ahead and get to work in this lecture i'll show you how to navigate one of my courses on coursera and while this probably isn't the course you're currently enrolled in that doesn't really matter all the courses that i do on coursera are structured pretty much the same so let's go wander around one of my coursera courses here's the home page for the course for you and you can scan different information about the different weeks in the course i typically would go to one of the weeks in the course and this particular week has a module and the module is starting to program there are a variety of learning objectives for this particular week there's a getting started lesson that will typically have some videos in here a course introduction this video i'm recording right now and a meet the instructor video and then there's another lesson here your first c plus code in this particular course and so there's a mix of videos and readings oftentimes exercises or other kind of readings and a discussion prompt typically at the end and then most commonly there's a programming assignment for you to complete so let's look at this programming assignment if i click it you'll see i've passed wow i could do the programming assignment there are instructions that you should follow very carefully each of these steps or comments or sentences in the instructions matters so you should read them all and do them and then when you're ready to submit you click the my submission button you click create a submission and you upload a file and you say you're going to abide by the honor code and then you submit your assignment so i'm going back and i'm going to look at week two because if we look at this video integer data types for example i wanted to show you the resources that typically go along with each of the videos so if you go over here on the left and select download you can see there's a variety of things you can download you can download the lecture video you can download the slides this one actually has an extra reading and then i've got some zip files for in this particular course both visual studio final code and xcode final code so if you're in a course that you can use either visual studio on windows or xcode on a mac then i provide the code for both of those if it's all visual studio no matter which platform you're on then of course i just provide visual studio code but each of the videos that i generate code for i include the code as a downloadable resource for you so you should download that rather than trying to copy and paste from a video if you're trying to use some of the ideas from the code i generated in the video just go download the code and unzip this and then you can use that code okay also on the left in the navigation bar you can take a look at your grades and look at me i've got a hundred on all three programming assignments this particular course has a final exam a quiz at the end that i'm late doing but that's okay so this is where you can go to see all your grades the notes section you can add some notes if you choose to do so and they can be created from the video pages so you can capture notes for particular videos lots of people go to the discussion forums so for example if you went to the week one discussion forum there's a generic week one discussion forum there's a sub forum about the assignment that's due that week and there are sub forums for each of the exercises as well so there's lots of opportunity for you to interact with your fellow learners posting questions about the course material or specific graded or ungraded activities and people are generally reasonably active on the forums so that's a good place for you to go to ask for help if you get stuck on stuff the messages section if i send you a message it will appear here in the messages section so my guess is you will probably be picking in general a particular week to interact with and you'll work your way through the material for that week all the way through submitting the programming assignment and i expect that's in general how you'll interact with the page although of course you may well be active on the discussion forums as well and there you go that's how you navigate one of my courses on coursera this is the totally optional don't watch it if you don't want to meet the instructor lecture i'm tim dr t chamelard and i grew up in a small town in southeastern massachusetts named norton and after high school i went off to georgia tech to pursue a bachelor's in electrical engineering degree but i was only at georgia tech for a year so if you'd like pause the video and guess for why i only stayed for a year and then continue as one of my past students said i left for the love of a good woman so my girlfriend was in massachusetts georgia tech is in atlanta georgia and that was too far for me so i spent about a year and a half putting stuff into boxes and handing it to the ups guy and then i enlisted in the u.s air force went off to basic training went to technical training school and after about four months in the air force i got married so pause the lecture again if you'd like to decide whether that was the same girl i left georgia tech for or somebody else the answer is it is in fact the same woman and we are still married so here we are in the air force we went off to omaha nebraska for our first tour and then after 16 months the air force decided to send me to school full time to pursue a bachelor's degree in electrical engineering at georgia tech so i did get to finish that degree at georgia tech in electrical engineering and then i went off to officer training school and got my commission as an air force officer our first assignment in the air force was at los angeles air force base where i spent four years managing contractors writing software to help us fly satellites particularly orbital software was my general area of expertise we had our first two children both boys while we were in los angeles and i also pursued my master's degree in computer engineering at the university of southern california going to school night finished that tour after four years and went off to the us air force academy where i taught undergraduate computer science courses for two years now the air force academy is usually a four year tour but i only spent two years there so if you'd like to pause the lecture video again and try to guess why i only spent two years go ahead and do so the answer is the air force decided to send me off to umass amherst to pursue a doctorate so i am in fact a doctor of computer science so i don't actually help people and my entire family loved the part in treasure planet the movie where there's a non-medical doctor and he is trying to help somebody who's injured and he says i just sit here and i'm useless and i saw that movie with my entire family at the movie theater and at that line every single person leaned over and looked at me so everyone knows i'm a doctor just not a real doctor okay so i finished off that degree and went back to the air force academy for that full four year tour that i should have had in the first place and then my final assignment was to washington dc where i spent a couple years managing contractors developing web applications and the databases that support those web applications and then i retired from the air force so i've been at the university of colorado at colorado springs since 2003 and i've taught a variety of courses including graduate level software engineering courses undergraduate computer science courses and undergraduate game design and development courses all of which i created from scratch and in fact we now have a bachelor of innovation in game design and development and i teach many of the beginning and the final course in that particular program and i'm the program director for that program so at this point i exclusively teach game development courses i also spend a year and a half as an indie game developer in a company that i formed with my two sons and that's peak game studios and we did a number of games both on speculation and on contract so here are the games we built on speculation the two images on the left are a game called cat that's based on an actual board game so we got the license from the board game manufacturer and you can think of this as chess with lasers and you can actually download a free version of this game at this point from the burning teddy website i'll talk about burning teddy soon the other screenshot from the upper right is for a game that we didn't quite finish as we shut down the company once my sons sort of grew up and moved on to do other things and that game is called battle paddles and you should think of this as pong with weapons because that's sort of the big idea behind that game we didn't quite finish it but we'll get back to that game as well so on this slide are the games that we built under contract so as a company you know we went we got a contract to build some games and we actually got paid to build them and that was awesome so the two on the left are for educational games for eighth graders the one all the way to the left it was a set of four minigames to teach about physics and the title of that group of minigames was physics with neat details and if you think of the acronym for that it's pwned and so of course you know a little tongue-in-cheek game development of course and the lower one was to teach eighth graders about robotics so they would configure a robot with various attachments to go complete a number of missions again there were a few mini-games to do the upper right one is something called colorado history arcade we got a contract to teach fourth graders about colorado history and that game was deployed on the pikes peak library district website so all of the games we built as a company except for the colorado history arcade game were using c-sharp we happened to use xna game studio to do that um but now of course we've moved on to unity the company hasn't but i have and so that brings us to this next slide where i tell you i now have a small company and by small i mean just me called burning teddy and i use that company to publish textbooks and online courses and of course also to do game development so that battle paddles game that i showed you the screenshot from i am in the process of porting that over from xna game studio to unity that is about 60 000 lines of code so it's going to take a little while to port but at some point that will be on the burning teddy website burningteddy.com and i'm also working on another smaller casual game that is called balloons extreme and i'll actually post my progress on burningteddy.com as i build that game in unity so burning teddy all the game development i'm doing is actually in unity so when i'm not teaching and i'm not doing game development what am i doing well a number of different things but one of those things is cycling so riding a bike is one of my joys in life i guess so these are my three bikes the blue one is the oldest one and that's really an old bike at this point but i used it to really get into cycling and not racing so much but doing long rides like a number of centuries which are 100 mile bike rides including at the time one of the 10 toughest centuries in the united states and so that century had over 10 000 feet of climbing that's what makes 100 mile bike ride harder than another is you know elevation gain and so i did a number of bike rides the mountain bike the one on the bottom is a result of going mountain biking with some friends one day and i loved it so much that i went out and bought the mountain bike the next day the bike all the way on the right is my triathlon bike so you know being a cyclist i did a lot of long rides i also did a bunch of running including a number of marathons and a running race that goes from the bottom to the top of pikes peak here in colorado springs i did that running race multiple times and once you've biked a long time and run a long time you say well you might as well do some triathlons as well just add a swim and you'll be fine and so i've done a variety of triathlons all the way from sprint distance which are really short all the way up to an ironman distance race i also play guitar i started doing that way back in high school and then gave it up for decades while i was raising my family and doing other things and now i've started up again to try to learn how to do it even better than i used to so moving from left to right the acoustic is a yamaha acoustic that i bought way back when while i was just out of high school the next guitar is a joe strummer replica fender came out with a joe strummer tribute guitar some years ago and that was my starting point but i replaced the three saddle bridge with a six saddle bridge because that's what joe strummer used i got to that relict pick guard from a place called axe stream creations and i even took the stickers that were on joe strummer's guitar and cut them into the shapes that they were worn into by the time a joe stopped playing the guitar and affixed them to the guitar in the appropriate places the next guitar is a gibson les paul gold top from a couple of years ago and the one all the way on the right is my most recent guitar that is a fender stratocaster american professional 2 and i didn't have a strat so i wanted to strat but i also couldn't resist getting it in the gorgeous miami blue color really the other thing other than you know interesting like you know reading books and stuff like that the other leisure thing i do is i play video games that should come as no surprise to you and so the question is what kind of video games do i play and you should pause the video guess in your mind what those might be and then you can move on to see a screenshot of what i use to play my video games you can see racing games are my passion so really racing simulations so you know realistic racing games rather than arcadey racing games and if you're interested in all the details of that racing rig you can go to the pdf that i've provided as a resource for this lecture so there you have it none of this has anything to do with course content but it gives you a little more insight into who's teaching you in the course what will you learn about in this lesson you'll learn about the bool data type in boolean expressions you'll learn about the selection control structure which lets us make decisions in our code you'll learn about if statements you'll learn about switch statements you'll learn how to implement a manual timer in unreal you'll learn how to build a spawner using the built-in unreal timer system and you learn how to use gameplay tags this lecture is about booleans but what are booleans booleans are things that can only evaluate to true or false and booleans are really helpful to us as we implement the selection control structure because they let us decide which code to execute we do get a data type in c plus and it's called bool and not surprisingly this data type can only evaluate to true or false so having a data type lets us declare variables of type bool or say a function that we've written returns a bool so it's really useful to have a boolean data type we also get this thing called boolean expressions and boolean expressions can also only evaluate to true or false and we build up boolean expressions using two kinds of operators the first kind of operator is called a logical operator and we'll talk about three of them the first one we'll talk about is and and the way and works is if we have two booleans and we end them together the only way that that boolean expression evaluates to true is if both of those operands are also true so true and true is true and the other combinations true and false false and true and false and false are all false the second logical operator we'll talk about is or and the way or works is with two boolean operands the or operator evaluates to true if one or both of the operands is true so true or true is true true or false is true false or true is true the only way or evaluates to false is if both operands are false false or false is false the third logical operator we'll talk about is actually something called a unary operator it's called not and not simply negates the single operand we provide to it so not true is false and not false is true the other kind of operator we use to build up boolean expressions is called the relational operator like equal equal not equal less than less than or equal greater than or greater than or equal so these are operators that we apply to determine the relationship between the two operands and these should be more familiar to you right 3 less than 2 is false 3 greater than 2 is true and so on so they determine the relationship between the two operands to recap in this lecture you learned about booleans and how they're useful in helping us implement the selection control structure and you also learned that c plus gives us both the bool data type and boolean expressions in this lecture you'll learn how to implement the selection control structure to make decisions about which code we're going to execute using if statements so what kind of decisions might we want to make we might want to decide if an enemy will drop loot or not we might want to decide if the player has leveled up we might want to decide what menu to go to and lots of other things so there's lots of decisions that we make in our code and if statements help us make those decisions in its most basic form the if statement has a boolean expression that's why we talked about boolean expressions it has a boolean expression that evaluates to true or false if the boolean expression evaluates to true we follow the true branch and do something as shown in this diagram and if we follow the false branch because the boolean expression evaluated to false then we just don't do anything and we move forward in our code let's go see what this looks like in c plus here's the code we'll start with all i've done so far is i've provided an answer variable and i'm prompting for and getting user input so here's my prompt pick up the shiny thing one for yes two for no and then i read in the user's answer down here where we're going to print an appropriate message is the interesting part so we'll start by adding a basic if statement so we say if and then we put open and close parenthesis and in between these parentheses we're going to put a boolean expression an expression that evaluates to true or false and then we'll put curly braces for our if clause and we'll put whatever code we want to execute if that boolean expression is true inside the if clause so let's handle picking up the shiny thing first if answer is equal to one that's two equals as the relational operator not one equal like that it's two equals so if the answer is one we'll print out a message you have the shiny thing like that so the way this will work is i'll run it and show you if we enter a one it will print out you have the shiny thing and if we enter anything other than a one even two it doesn't say anything so the execution checks this boolean expression and if it's true it does this and if it's false it just goes past the if statement to the end of our main function now we can do something on the false branch as well so if the boolean expression evaluates to true we go and we do something and then we move on in our code and if the boolean expression evaluates to false we do something else and then move on in our code let's go see what that looks like in c plus plus now we'll add in else which will be executed for every input other than one so if this boolean expression evaluates to true we'll do this and go past the entire if statement but if the boolean expression is false we'll go to this else and will do whatever we say to do in the body of the else statement and they decided not to pick up the shiny thing so now if we run our code if we enter one we get you have the shiny thing if we enter 2 we get you don't have the shiny thing unfortunately the way else works is even if they enter 3 we say you don't have the shiny thing and while that's true they didn't pick up the shiny thing it's also true that they didn't give us one of the valid answers so we should in fact tell them that they gave us an invalid answer we also might want to have multiple alternatives specifically more than two alternatives that we evaluate in our if statement and even though this structure i'm showing you doesn't go along with the example we're doing you can see that we have a cascade if you will of if alternatives that we want to handle within our if statement and we do those alternatives between the if and the else we do those alternatives using something called else if let's go see what that looks like in our code we need to take this piece of code and put it into an else if clause so we only do this if they've entered two so we'll see how that works as always we make sure one still works we make sure two works you don't have the shiny thing and now if i enter three i don't get any message at all now i would like to actually tell them that they've messed up so i'll add an else here and here i'll print out a supportive message to the user telling them in a gentle way that they didn't provide valid input so i'll say invalid input dork so now the way it will work is we start at the top and we work our way down we get here and if this boolean expression is true we execute this code and we go all the way to the end if this boolean expression is false we drop down here and we check this boolean expression and if this boolean expression is true we do this and leave the if statement and then finally if this one is false also so this one was false and this one was false we do whatever is in the else so let's watch that in action one gives us the shiny message 2 gives us the not shiny message and 3 or any input other than 1 or 2 gives us the invalid input dork message and i'll put that new line there as well so as you can see we've used an if all by itself we used an if with an else we used an if with an else if and we used all three and of course we could have more else ifs in there too so the rule for an if statement is you need an f no matter what you can have zero or more else ifs as many as you want including none and you can have zero or one else clause you can omit the else clause like we did at the very beginning or you can include it you can't have multiple else clauses that doesn't make any sense but you can have zero or one to recap in this lecture you saw how we can use multiple variants of the if statement to implement the selection control structure to decide what code executes in our program in the previous lecture we explored how we can use multiple variants of the if statement to make decisions in our code in this lecture we'll use another statement the switch statement to make decisions in our code let's go take a look we're starting with the code we ended up with last time from our if statements lecture so we have that variable and we prompt for and get user input except here we're not going to use an if statement to print an appropriate message we're going to use a switch statement instead for our switch statement we put the switch keyword followed by parentheses and in the parentheses we're going to put the variable that we're going to switch on so we're going to use our selection logic on the answer variable just as we did down here in our if statement however within a switch statement we put a set of cases so starting like we did before where we were only responding to one as an input when answer is one we'll say you have the shiny thing the other thing that we'll put at the end of each case is we'll put a break and that says break out of the switch statement go to the line after the closed curly brace for the switch statement so if i run this code and i enter one it says i have the shiny thing and if i enter anything else it doesn't print anything remember the next thing that we did when we did the if statement lecture is we added an else clause to our if and remember the else clause gets executed if none of the other alternatives in our selection have been executed if none of those above the else clause have been executed then the else clause gets executed we have a similar thing within our switch statement it's called default so default will be executed if none of the cases above default were executed following the same pattern we did before we started off in the previous lecture by using the else to print out you don't have the shiny thing and we put a break at the end of the default clause as well and then we saw that we could do one and we could do two and then we were disappointed to see that we could also do three and it said you didn't have the shiny thing so of course what we want to do is make this specific to answer having a value of two and then we'll add that default clause back in but we'll print the invalid input message here remembering our break and now one works the way we expected two works the way we expected and three works the way we expected and just so you don't think i'm trying to do anything crazy 42 also works as an invalid input so the default is the else right it's if none of the cases above applied in the switch statement then the default clause gets executed if we include one we don't have to include one but it's generally a good idea to include a default clause in your switch statement and that's it we've converted our if statement structure to get the same behavior out of a switch statement because a switch statement also gives us a way to implement the selection control structure to recap in this lecture you learned how to use the switch statement to make decisions in our code implementing the selection control structure in this lecture we'll look at how to implement a timer actor component and i'm calling this a manual timer because unreal actually has a built-in timer system that we'll learn to use very soon but i wanted to do this example to show you both how actor components work and also to show you a compelling example of where the selection control structure is really useful in a game timers are also really useful in our games so when are timers useful in our games they're useful in timed levels so we can decide when to end the level they're useful when we're deciding whether or not to spawn something they're useful for weapon cooldowns they're useful for deciding when to increase the difficulty in the game and lots more so let's go look at how we can implement that timer actor component as i've mentioned before when we create a new class or a new script in unreal we actually get two files we get a header file that ends with the extension dot h and we get an implementation file that ends with the file extension dot cpp for c plus we'll look at the header file first for our timer and you'll notice here that the class name is actually you timer not timer when i created the script i said i wanted it to be a timer script and the unreal engine prepends a u to the class name so the actual class name for my timer is you timer and you'll notice here that when i created it i said it wanted to have actor component as its parent class not actor as we've done previously but actor component and the reason i selected that as the parent class is because we won't add a timer as a standalone entity into our map instead we'll attach timers to actors that should have a timer associated with them remembering that this is just an exercise and seeing how we could do a manual timer with if statements will really use the built-in unreal timer system when we need timers in our games but this is a great example of using actor components and it also lets us solidify our understanding of how if statements work in our header file so i'm in timer.h here in our header file i've declared an area that's private in other words consumers of this class can't access these variables and i'm calling them fields here because they are variables we declare them like variables but they're visible throughout all the code in our class so instead of having a variable that we have just inside a particular function these will be available throughout our class i have a bool variable called b running and this variable will tell us whether the timer is currently running and i set that to false because when i create a timer it's not running yet i have a bool variable called be started that i set to false and i'll talk about why i need this additional variable soon i have a floating point variable for the elapsed seconds that the timer has been running since it was started and i set that to zero and finally i have a floating point variable for the total seconds and that's also set to zero so the way we use elapsed seconds in total seconds is total seconds say how long is the timer supposed to run and for this lecture that's three seconds and then a lap second says how long has the time have been running since we started it and so when elapsed seconds reaches or exceeds three seconds the timer should stop so a lap seconds keeps track of like the running time that's accumulated since we started it and total seconds tells us when to end this debugging variable is not needed in this lecture but i did use it as i was talking through in the book the full development of this class the rest of the stuff that we put in our header file includes a constructor that we're not going to use it includes begin play which we will use it includes tick component so in the past we've always said should we let the actor tick should we call the tick function on every frame of the game and we've always said no but this time we're going to say yes we actually do want to tick this timer every frame so we can update elapsed seconds we have a getter that tells us if the timer is finished and we need that because if we start a timer we probably want to know when it's done we have a getter that tells whether the timer is currently running because we may be curious about that we have a setter a set duration function that lets us say how many seconds we want the timer to run and finally we have a start function that actually starts the timer so the structure even though you're not yet designing your own classes the structure of a class is in our header we put our fields and our functions and the fields will always be private we'll talk about good design processes as we keep moving forward but the functions will be either private for internal helper functions that the class needs but doesn't want to expose to consumers of the class and public functions like these that we've exposed to anyone who has a reference to a timer object in our implementation file in our constructor here's where we say we do want to tick i lied about begin play we're not actually going to use it in our implementation here in tech component here's our first if statement if we're currently running and you might think we should do this if b running equal equal true and that would work but b running is a boolean already so if b running is true we update our elapsed seconds and the way we do that is we add delta time to elapse seconds so this is actually the same as this those two lines of code do exactly the same thing but you'll see most experienced programmers just using this syntactic shortcut to add delta time to elapsed seconds so it is delta time delta time is the amount of time it's been since the last time tick component was called so this gets called every frame but as your frames per second change in your game delta time would change sometimes it would be larger sometimes it would be smaller so this gives us a good way to update no matter what our frame rate is or how it's fluctuating so if we're currently running we add delta time and then we check to see if we're greater than or equal to total seconds and if we are we just stop running now you might think you could check equal equal here but that's a really bad idea because if a lap seconds was 2.99 on one frame and then it was 3.01 on the next frame elapsed seconds would never equal total seconds and our timer would never finish so we always want to check greater than or equal to when we're trying to reach a certain point but if we exceed that point that also means we've reached it our is finished getter tells us whether the timer is finished and here's why we need that b started field because if we just said return not be running as soon as we created the timer we would say it was finished because it's not running right now so we want to only say the timer is finished if it's not running anymore but we did start it at some point is running is really easy we just return b running setting the duration we do some error checking in here so this is why it's really good not to just let a consumer of the class directly access total seconds which is why we made it private we'll say here we won't add time if it's running already and we won't set a negative duration because that doesn't make any sense for a timer and starting the timer is really straightforward we make sure we have a valid duration and if we do we start it we say it's running and we set a lap seconds to zero which by the way that debugging code you see sprinkled throughout when i first implemented the timer i did not have that line of code and it wasn't working and if you want to you can go check out the selection chapter of the book to see how i discovered that and how i fixed it well how i fixed it was i put this line of code right where you see it in this lecture we learned how we could implement a timer actor component using the selection control structure in the previous lecture we learned how we could implement a timer actor component in this lecture we'll see how we can test that timer actor component okay so that's the timer class but remember it's an actor component and so we're going to want to attach it to an actor and that's one of the reasons i wanted to do this manual timers lecture even if we're going to use the unreal timer system later because this shows us how we can work with actor components and we're going to do that with our timer test actor so here in the header file for our timer test actor which you can see is a child of the actor class and it's called a timer test i have some private fields here i have you timer for my timer but that asterisk right there is something new for us so that asterisk says this timer field is actually a pointer to a u-timer object it's not an actual u-timer object it's a pointer to one and we'll see why we need that later and we'll also discuss pointers later but you can just think of this variable as holding the address of the object not the object and we'll have a couple of syntactic things to do as we deal with pointers but we'll explore them in more depth before we're done with the entire specialization fda time is a built-in unreal type for date and time so we've left the rest of this the public constructor the protected to begin play and the public tick we've left all those the way they were when we created the script in the implementation file for the timer test script we're going to let the timer test script tick on begin play you can ignore those red squigglies on check sometimes visual studio gets confused right usually in a console app for example red squigglies would mean this thing will not compile but when visual studio is attached to unreal sometimes it will mark things as errors and they're not so this is not an error that particular red squiggly okay so this part here is about using an actor component one of the reasons we're doing this video so the comment says add check and register the timer component so first we take our field and we want to put a new pointer to an u-timer object into that field we don't use our typical form for constructing an object in unreal instead we say new object we want a new object and we want it to be of type u timer and this says who's going to own this new object that's getting created and for us it's going to be timer test and this whole thing returns a pointer to a u timer object and that's why we need timer to be a pointer to a u timer not just a u timer so we have to work within the constraints of how unreal works and unreal wants to give us pointers so we'll just use pointers this next line of code that is confusing visual studio is called an assert when we put check we're making an assertion and if our assertion is false our game will crash and it'll stop right here and so we want to check to make sure timer that pointer that just got returned to us is sorry about that is not equal to a null pointer in other words this did not fail it succeeded and gave us a pointer to a u-timer object so this is just making sure that happened fine before we actually start trying to use the timer field this next line has a couple of things first of all we're calling a register component function and we'll talk about why we do that in a moment but what you've learned for classes and objects so far is you would have expected this to be timer dot register component using the dot notation we use the dot notation when we have an actual object not a pointer to an object so to actually call a function on a pointer to an object it's most convenient to use this arrow notation and so we're doing essentially the same thing but there's one more step along the way we're actually doing what's called dereferencing the pointer to get access to the actual object and then using dot notation to call the function but using this arrow notation is just cleaner but why do we have to call this register component function at all the reason is this is the chapter of the book the reason is that the unreal engine components documentation tells us in order for actor components to update each frame which we need our timer to do and affect the scene the engine must register them so whenever you add an actor component that you want to tick every frame and have some effect you need to register it now we set the duration for that timer to three seconds and we tell the timer to start the rest of this stuff is just keeping track of how long the timer ran including down here when we check whether it's finished in our tick function in the timer test so i'll let you just go read the chapter in the book that does this it's just calculating the elapsed time each time we run the timer so i'll compile just to convince you that those red squigglies don't actually prohibit us from compiling and i succeeded here so we'll come over to the unreal editor and select the output log so we can watch as the timer goes along running approximately every three seconds now this 2.934 at the very beginning is a side effect of when i get the current time and when i tell the timer to start and as you can see it's running every three seconds as expected to recap in this lecture we saw how we could test the timer actor component that we implemented in the previous lecture in the next two lectures we'll see how to use the selection control structure in the unreal engine timer system to build a spawner in this lecture we'll build the blueprints that we're going to spawn and we'll also learn how the u property macro works i've already implemented all the code for the required functionality for this lecture but i'm going to show you how i've done that and we'll start with the teddy bears dying after 10 seconds i'm just going to run the game to show that happening and as you can see i placed some teddy bears into the map and we just watched them bounce until their 10 seconds timer ends and they disappear so this was one line of code to actually make this happen so over here in the teddy bear implementation file i changed can ever tick to false because we don't need it to tick but in the begin play function i set the life span to 10 seconds so we can set a life span for any actor we've got and i set this to 10 seconds so after 10 seconds expires unreal destroys the teddy bear that was the easy part the harder part is adding the teddy bear spawner let's take a look at the header file first for the teddy bear spawner and i have a pound include for the teddy bear dot h here and i'll show you why in a moment so we scroll down and i have some constant that i want to use for the spawning process i have a min spawn delay seconds of one second and a max spawn delay seconds of two seconds so we'll do a spawn somewhere between every second and every two seconds we'll change the spawn delay each time we complete a spawn so that we don't just spawn at a regular interval we have some randomness to that i've also added a min spawn y and a max spawn y so that we're going to just be spawning our teddy bears inside the screen when we spawn them and i have a min spawn z and a max bond z for exactly the same reason i'm not spawning down at the bottom of the screen that's why my min spawn z is a zero but i'm going to spawn up as high as 100 in our map so this should look somewhat familiar to you we've seen constants and we've seen floats and we've seen variable names and initializing those variables with the braced initializers i also have a start spawn timer function but you'll notice up here i've said that that function and all these constants are private so they're only accessible inside the teddy bear spawner we'll talk about class design later and we'll talk about why this information hiding is a great idea i know we've addressed information hiding when we talked about classes and objects but this is a good idea to keep all these things private because they're only needed inside the teddy bear responder a very new thing is this you property stuff so we're marking this field and this field and this field as unreal properties using the you property macro so what we've put in here are the uproperty macro this edit anywhere is called a property specifier and i will tell you as i talk about these items or elements that we put inside the you property macro the best thing to do is to go explore the documentation for you property if you decide to you want to use it in a different way from the way we're using it here but here i'm setting this you property as edit anywhere and then i'm providing a metadata specifier which basically says for this property you can only populate a list we'll see that we'll have a populated list of classes that we can use to populate this particular property so this says only those classes that are either a teddy bear or a child class of a teddy bear remember we pick parent classes or when we create blueprints we say create a blueprint class from this c plus class and that's what i did here but i did all of them off of a teddy bear all the blueprints we have for our teddy bears and so when we populate a list which i promise i'll show you soon we will only include those classes in the list and we can also say give us a particular category that we can look at for these properties so you might in a larger game you might have a bunch of view properties and a bunch of different classes and they would be different categories of classes you want to include and so this is a way to set it up so that in our blueprint editor we can actually have things categorized finally i have a field because this will be visible throughout the teddy bear spawner class i have a field that i've called you green teddy bear green teddy bear because it's a green teddy bear i put you in front of it because i wanted to do that it's actually a you class which is what blueprints are and the data type i said is it's a subclass of a teddy bear so this is sort of the c sharp part of saying i only want teddy bears here i'm saying the you green teddy bear is going to be a subclass of the a teddy bear class so i have these three properties for green purple and yellow teddy bears so that i can randomly pick which one to spawn when it's time to spawn it let's see how this property stuff works in the editor so here in the editor if i navigate to my teddy bear spawner blueprint and double click it to open the blueprint editor you'll see here under teddy bear blueprints i have my you green teddy bear field my you purple teddy bear field and my you yellow teddy bear field and these are appearing here because i marked them as you properties and they're appearing here under the teddy bear blueprints heading because i said that's what category they belong to i can select over here on the right for my you green teddy bear i can select the green teddy bear blueprint i created from my a teddy bear c plus plus script or my purple teddy bear blueprint or my yellow teddy bear blueprint or my base class and i'm not going to pick my base class i'm going to just pick the green teddy bear and as you can see i populated each of these things so using the u property macro makes it so we can populate these fields in the blueprint editor rather than trying to do it within our code there is a way to do it within our code but we're going to do it within the blueprint editor instead so i did change this so i'll compile and save it in this lecture we learned how we can build an actor with a set lifespan and we also learned how the u property macro works in the previous lecture we built the blueprints we're going to spawn and we also learned how the u property macro works in this lecture we'll use the selection control structure and the unreal engine timer system to actually do the spawning and we'll go back to the teddy bear spawner code and the other stuff in our header file are the default things we typically get so in our implementation file in our begin play function we call our start spawn timer function which we'll look at soon and in our spawn teddy bear function we declare a variable for the teddy bear we're going to spawn it's also a t subclass of a teddy bear we generate a random number zero one or two inclusive and if that number is one we set spawn teddy bear to the green one if it's one we set it to the purple one otherwise we know that teddy bear number is two so we set it to the yellow one so here's an instance of using an if else if else to do something interesting in our game to randomly select which teddy bearer blueprint we're going to spawn into the map next we generate a random spawn location so f vector is a floating point vector a three dimensional vector and we'll declare a spawn location variable that is an f vector and i read the f vector documentation to determine that i wanted to use 0 here in the constructor to set x y and z to 0. you know i want x to be 0 because we're making 2d games but setting y and z to 0 initially also makes a lot of sense i also learned in the f vector documentation that the f factor class exposes a set component for axis function and here is that function in the f vector documentation and if i click on it i see that i provide two arguments when i call this function i provide which axis i want to set x y or z and i provide the value as a floating point number that i want to set that component to so this e-axis thing looks a little strange to us if i click on it we can see that e-axis is something called an enumeration which we haven't explored yet so an enumeration is a data type that can only have specific values so if i have something that is of the e-axis data type it can only have the value none x y or z so when i come back to my code i'm saying here that the axis that i want to set is the y-axis and i put the name of the enumeration and then colon colon and then the value i want to use so if i try to use something like e axis bob here this won't compile the intellisense tells us right that it's none x y or z and so the enumeration makes it so i can't provide an invalid value i can mistakenly try to change the x-axis here instead but i can only use those possible values in the e-axis enumeration so i'm saying i want to change y and now i call rand range and i say min spawn y and max spawn y so i will be spawning at a random location in y between min spawn y and max bond y i do the same thing to set my z axis between min spawn z and max pawn z so at this point in my code spawn location has a random y and z in the ranges i set with those constants in the header file and x is zero to spawn the teddy bear i first call get world so the get world function is a getter for the cached world pointer which basically is a pointer to the world in which this actor exists and by world we mean map so first we get a pointer to the map that this teddy bear spawner is placed in then we call spawn actor and spawn actor is a templated version of spawn actor that lets us tell the location in rotation as well as the class type that we want to spawn via the template type in other words we put the class we're trying to spawn here and because all of our blueprints were generated from the a teddy bear c plus plus script this will work great for all our blueprint we say what we want to spawn and this is the teddy bear that we generated up here we say where we want to spawn it which is this random location that we set up here and i read the documentation to figure out how to actually do it with no rotation once we've spawned a teddy bear we start the spawn timer again before we go look at how the start spawn timer function is implemented i feel like i might have misled you a little because i was so excited to show you how enumerations work so this is certainly one way that we can set the y and z components of our spawn location variable however there is in fact an easier way i'll comment out those and i'll show you that i can also directly say spawn location dot y is equal to this and spawn location dot z is equal to this and that's definitely the more common way to change the y and z components of our f vector but i was excited to show you about enumerations so there you go you learned about enumerations but this is the more common way to do it okay let's finally look at how the set spawn timer function is implemented so here's how we set our spawn timer first i'm going to generate a floating point number that is a random float between min spawn delay seconds and max bond delay seconds so at this point timer duration is holding how long we want the spawn timer to run somewhere between one second and two seconds next i'm declaring a variable called timer of data type f timer handle and the way i learned i needed an f timer handle variable was because i read the documentation for how to actually set a timer i start by calling the get world timer manager function which gives me the timer instance from the actors world so we're using the built-in unreal timer cistern and this gives us the timer manager that we need for this particular map the map in which the actor lives so this returns an f timer manager and if we click on f timer manager we discover that the f timer manager object that we get back has a number of set timer functions in fact it has one two three four five six six different functions for set timer we're actually going to use the last overload and it turns out that the last two parameters here are optional so we don't need them but this first parameter that we need to provide an argument in our code needs to be an f timer handle so the first argument i provide here is that variable that i declared on the previous line next we say that we want to use the timer here in this particular object and then we provide the address of a function that we want to get called when the timer expires not just the function name but the address of the function and finally we say how long do we want the timer to run and that's the timer duration that we generated right here so what will happen is this starts the timer when the timer finishes after timer duration it will call our spawn teddy bear function which we already looked at is right here and that function will pick a teddy bear to spawn generate the random spawn location spawn the teddy bear and start the timer again back in our game i will need to actually add the spawner to the map to make it work and once i've done that i can just alt p and we can see that we're spawning new territory bearers every one to two seconds i know we got a few yellows in a row that's just how it works and as you can see the spawner is also working properly spawning new teddy bears into the map to recap in this lecture we saw how to use the selection control structure in the unreal engine timer system to spawn our blueprints in this lecture we'll look at how we can use the selection control structure in conjunction with something called gameplay tags so this game is identical to the spawning teddy's game except that we're going to destroy teddy bears periodically as well and the mechanism that we're going to use to destroy teddy bears is something called the gameplay tags so it's really useful to be able to tag particular blueprints or actors in our map with a label or a tag so that we can go find them later is one of the most common uses of tags so we can actually apply multiple tags to each blueprint if we want but we're only going to use one tag per blueprint here the first thing we need to do is actually add a gameplay tag to apply to those blueprints so we go to edit project settings and we select gameplay tags and i've actually already added a tag called destructible to my game the way you add a tag is you click here and you type in the tag and then you add the new tag and then the new tag is included in your game so i already did that i added a tag but this is our first step we add a tag one or more tags to our gameplay tag list here in project settings that makes that destructible tag available for application to any blueprint so if i open up the blueprint editor for the green teddy bear blueprint and over here in details i scroll down you can see under the actor section i have tags and right now i have applied one tag to this blueprint i could add multiple tags as i said but i only need one and when i go to add an element i click here and i type in the name of the tag that i want to add typically we won't add none as a tag i would type in the tag that i wanted to add but i don't actually want two tags on this blueprint so i've just gotten rid of that but you have to remember the exact string you used for the tag to actually type it in again here but now that i've done this the green teddy bear blueprint now has the destructible tag attached to that blueprint and of course i did that to the purple teddy bear and the yellow teddy bear as well so where do we actually do this destruction stuff well we're going to use something new we're going to use something called a game mode so let's look at the unreal documentation so a game mode is a mechanism that we can use to set some of the rules of our game we actually could have set up the spawning of our teddy bears in a game mode as well but i actually wanted to have that as an actor so that i could sort of add multiple spawn points if i wanted to and not generate a random spawn location then actually just spawn things out of those spawn points so i wanted an actor for my spawner but we'll use a game mode for our destroyer and we'll continue to use game modes as we move forward in the specialization when it's appropriate for us to do so so in this lecture i'm going to use a game mode to implement the destruction functionality let's go take a look at that game mode so i called this a destroyer game mode and it will destroy a destructible tagged actor every second i have a private function called start destroy timer that should look familiar to you because remember i had a private function called start spawn timer in my teddy bear spawner class and i have a function that we can call to destroy a destructible and we'll see how that works once we get into the implementation file of our destroyer game mode and this is just the default begin play in my implementation file on beginplay i start my destroy timer much like i started the spawn timer before we'll come back to destroying the destructible i just wanted to show you this function looks a lot like the start spawn timer except this time we're just doing it the comment said every second i'll go fix that it's every three seconds but this is the same thing we're not doing it randomly this time we're just doing it every three seconds consistently so let me fix this comment because we always want our comments to actually match what the code does otherwise they're misleading so the interesting stuff for this particular lecture is using tags so we say here we're going to destroy destructible and just like in our spawn timer we provided an address of spawn a teddy bear here the spawn teddy bear function here when our timer goes off we're going to call our destroy destructible function now this uses some new stuff that we haven't seen before but we are going to have tagged actors and really what we're going to have is we're going to have an array we're going to talk about arrays soon but i really wanted to use tagging here but our tagged actors variable will be a t array of pointers remember that asterisk notation of pointers to actors so an array is just a way to hold multiple things so we're going to go find on the next line of code we're going to go find all the actors that are in the map with our destructible tag and we need to store them somewhere and there could be more than one of them there may not be but there could be more than one of them so we need a way to store multiple pointers to actors in a single variable and so the way we're doing it is with the t array i know i'm waving my hands a lot so just sort of squint at that that's not really the important piece here the important piece here is the next line of code so ugameplaystatics the class has a get all actors with tag function right here and when we call this we need to provide a world context object which we can get with a call to the get world function like we have before we provide the tag that we're looking for so that's destructible again you need to spell this correctly and have it exactly match your tag and we also provide it with the t array of a actor pointers that it can populate with all the actors it finds and that's why tagged actors is declared to be of this data type there is a remark here that's important and that remark is this is a slow operation finding all the actors in a map with a particular tag is slow so we don't want to do it on every frame we aren't doing it on every frame we're actually only calling destroy destructible every three seconds so we're willing to eat the inefficiency of doing this because we're not doing it regularly then we check to see if we got at least one and if we got at least one then the very first one and we'll see why we use zero and we talk about arrays the very first tagged actor we call the destroy function on it and it destroys that actor and then we start our destroy timer again so that we can do this again three seconds from now so this part right here is the piece that tags make really useful for us because by tagging our actors our blueprints we can go find them in the map when we want to do something and this time we just want to destroy one of them so finally if we actually run the game we'll see teddy bears spawning into the map and then every three seconds we're going to try to find all the tagged actors and then we'll destroy one of them so i started the game and we spawned a purple one and it disappeared immediately and now we got rid of a green one and we're going to get rid of that green one so if you watch you'll see that we are destroying teddy bears periodically as we run the game there's finally a purple teddy bear as well the last thing i'm going to mention is i set a different game mode destroyer game mode that i wanted to use here and i actually need to go to edit project settings and under maps and modes which we've used before to set these maps i need to set the default game mode to the destroyer game mode that i wrote otherwise that game mode just doesn't get used when i run the game and that's how we use gameplay tags in a useful way in our games to recap in this lecture we learned that we can add tags to blueprint so that we can find them and process them based on their tags what will you learn about in this lesson you'll learn about action mappings and access mappings in unreal you learn how to process mouse input you learn how to process keyboard input and you learn how to process gamepad input in this lecture you'll learn how to use the mouse location in your unreal games so let's go take a look in this lecture we'll create two new scripts and we'll use the mouse input game mode base script that unreal automatically provided to us when we created this project because we're going to write a custom game mode like we've done before the other two scripts i've created here are a character pawn and a character player controller so as i mentioned the big idea is the pawn is the avatar for the player in the game and the player controller will possess the pawn to make it bend to its will if you will so we've got the pawn to represent the player in the game and then the player controller will control how the pawn behaves before we look at those three scripts i'm going to navigate to the blueprints that i have in the game so i have turned the character pawn script into a blueprint and i gave it a static mesh representation so we can see it in the game and i turned the character player controller into a blueprint that as well so i've converted those two scripts to blueprints we'll look at our custom game mode base for this project first so i've added a constructor here this doesn't come for free when we have the gamemode base as the default that gets created by unreal so we need to add a constructor for it and here's where i do some serious work so what we need to do here in our custom game mode is we need to set up what the default pawn is in the game and what the player controller is that controls that pawn because i have these as blueprints i'm going to use this f object finder class that's a templated class so we say what kind of object are we looking for and blueprint classes are of the data type u class and then i tell it what i want to name this variable and then i have this really interesting stuff here that says where can i find that blueprint class definition back in the editor the way we get a location of a blueprint is we right click on the blueprint and we say copy reference now i'm going to copy that reference into the code even though it's not quite correct for what we need and i'll show you how we can change it so i'll just find a blank space here to put it so if i control v now i actually have a reference to the blueprint itself not the blueprint class and i want to reference to the blueprint class so i take what i got here and i put it between the double quotes here and the two changes i make are i changed blueprint to class and i put underscore c at the end because that's what unreal does to name the blueprint class that goes along with this blueprint so i want to load the class here so that's what i'm doing next the f object finder class has an object property that will tell us the object for the asset that was loaded and i'm checking here to make sure that's not a null pointer if trying to load this pawn class fails then pawnclass.object will be no and i better not do anything with it so this is my safety check to make sure that worked properly and if it's not null finally i can set the default pawn class the class of the default pawn in my game to pawn class dot object i do a very similar thing for the player controller i turned it into a blueprint so i use this line of code to go find the class associated with that blueprint i make sure that i didn't get a null pointer and as long as i didn't get a null pointer i set the player controller class to be controller class dot object so by doing this in my custom game mode what will happen is when the game starts unreal will automatically possess the default pawn class with the player controller class it will also place that default pawn at player start which is right here i've set it to 0 0 0 so it will put it right in the middle of the screen for me remember if we change the game mode we need to go to edit project settings maps and modes and here we need to set our default game mode and we're using the custom game mode that i was just working on and that's an important step if you forget to do that and you did all that work i just did if you forget to do that then when you run your game you'll just end up with a sphere in the center and you'll wonder why your character isn't showing up there and the reason is the most common reason is that you didn't remember to change the game mode okay let's see how the pawn class works next so here we are in the character pawn header file and these are default things we get we get a constructor we get a begin play function we get a tick function we get a setup player input component function because sometimes you can set it up so the pawn handles all its own input processing it's not possessed by a player controller i'm going to consistently throughout the specialization just use a player controller to possess the pawn or a different kind of controller if i set it up so that it has artificial intelligence it won't be a player controller it'll be an ai controller but something will possess all my pawns so we get this function by default but i'm not going to use it i did however add a function that will let a consumer of this class call the set location function so that i can move the pawn to a different location the way i move upon to a different location is i call this function set actor location and i do it with location and because a pawn is a special kind of actor it just moves the pawn to the provided location the most interesting stuff is in our character player controller script here in the header file i've added a player tick function and i need that because i'm going to make the pawn follow the mouse location on every frame and so i need to tick every frame to do that it's called player tick here in a player controller rather than tick like we've seen in pawns and actors but it does the same thing so in player tick i do a number of different things the tricky part is the mouse is in screen coordinates it's just this flat plane right that we move the mouse along but it's not in the game world it's just on our screen to get a world location so we can actually make our character follow the mouse we need to convert the screen location that the mouse is on into the world location where we want the character the way we do that is we use the d project mouse position to world function that appears in the player controller class and here's the documentation for that it says it converts the current mouse to d position to a world space 3d position and direction we don't really care about the direction here in our 2d games but in a 3d game you would care about the direction as well so we provide an f vector for the world location and an f vector for the world's direction when we call this d project mouse position to world function and that's why i declared these two variables before i call the function so now after i call the function when i get to line 23 here world location is the location in the 3d world that corresponds to the location of the mouse in the 2d space of the screen now we want to move our character to that location but before we do i want to set world location dot x to zero remember we're keeping everything on the y z plane so i'm going to move the pawn to stay in the y z plane how do i actually get the pawn well i call the getpawn function and that gets the pawn that is possessed by this playercontroller i will say that that actually returns an a pawn pointer and because i need to call a function on an a character pawn i need to typecast the results of that function call to be an a character pawn pointer and that works because an a character pawn is a special kind of apon because i picked pawn as the parent when i created this script and i put that into a variable called character pawn again for safety i make sure that that get pawn function worked fine by making sure character pawn is not a null pointer and if it's not i can now say on that character pawn pointer call the function remember this arrow notation is what we use if we need to call a function on a pointer to an object rather than the object itself and then i call that set location function that i showed you earlier and i provide the world location that i extracted from the mouse and set to the yz plane so back in the editor i can now run my game and i have this character so peak game studios actually built a number of games for the pikes peak library district to use to teach fourth graders about colorado history and that was a 2d flash game but my 3d character modeler turned those characters into 3d models that we can use here so this is one of the characters from that game and as you can see she follows the mouse around as i move the mouse around unfortunately if i drag the mouse outside the screen she leaves the screen as well including top and bottom as well of course and there may be some games where we want to actually keep the player in the screen and will address that particular issue in the next lecture so this is all the code and all the setup to make our character follow the mouse around the screen to recap in this lecture you learned how to retrieve and use the mouse location in your unreal games the title of this lecture comes from a song by one of my favorite groups of all time the clash so if you've never heard of the clash or you've never checked them out pause this video go check out the clash and then come back in this lecture we'll learn how to clamp the character's location so the character stays fully within the bounds of the screen more generally we use the term clamp when we want to keep a particular value within a range of values or a set of to support clamping our character into the screen i've added some constants for the screen so we put them in a namespace called screen constants the way i generated this particular script is over in unreal i created a new script with none as its parent and then i added the code i wanted here and deleted some of the code that was in the default script that was provided so in our header file i've got a new name space here we've used namespaces before but this time we're creating our own and i'm declaring four constants for the left right top and bottom edges of the screen i will say that there's certainly a way to calculate those boundaries using characteristics of the camera and so on but we're just going to set the constants because i know what the numbers are and this will be fine for us so we've seen const and float in variable names or constant names before but we've never seen this extern keyword before here's how it works constants in c plus plus have internal linkage by default and what that means is those constants are only visible within this translation unit not other translation units so other translation units are loosely although not precisely the other implementation files in our project and we want these constants to be visible from other implementation files specifically we want them visible from the character pawns implementation file so we need to mark them as x turn for external so that other translation units can access those constants the implementation file for the screen constants just gives values to each of those constants so this will be useful to the character pawn to know where the left right top and bottom edges of the screen are over in the character pawn header file i've declared some constants for the half width and half height of the character that we're using and a vertical offset that i'll talk about when we get there so the way i actually figured out the half width and half height for this character is i went to the actual static mesh and i opened up the static mesh editor and over here on the left it tells us the approximate size is six i know that's the depth by 25 i know that's the width by 32 which is the height so this is sort of a rough way to get the size of the mesh we could certainly if we replaced the simple collision that was automatically added when we imported the mesh if we removed that and added a capsule collider we could access information about the height and width of that capsule collider but that's overkill for what we're trying to do here so we'll just use this information instead so let's move to the implementation file for the character pawn and all our work will be in the set location function recall last time all this function had was this one line of code and i want to add some more lines of code to actually keep the character in the screen i will say because i'm using these constants from the screen constants namespace i had to add a pound include for the header file for those screen constants so if you forget to do this and you try to compile you get a number of compilation errors the first one is the trigger for the rest of them and it says screen constants is not a class or namespace name so whenever you see that error message your first thought should be i forgot a pound include okay so i've found included screen constants and visual studio takes a while to catch up to me realizing that i've done that but i'm going to use the clamp function in the f math class to clamp location y so that it falls between a minimum of left plus half width so you should think about this if i'm on the left hand side of the screen i have my location on the origin or the center of my model and mine is approximately in the center of my model so the left side of where i should be able to move my character is left plus half the character width and and that will make it so the left side it can't go past the left edge of the screen similarly i make the maximum the right hand side minus half width and i hand in the location i'm trying to move in it makes sure it stays between these bounds and i put that into location y i do something similar with z except that you'll see i'm using bottom plus half height plus vertical offset and top minus half height minus vertical offset and once we've clamped y and z to be within the screen we set the actor location but why do i need this vertical offset thing so let me change it to zero and i'll show you what happens after i compile of course when i run my game my character follows the mouse around the character clamps properly on the left and right but if you look carefully i can actually move part of her hat above the top and i can move she has black shoes on i can move her shoes down out of the bottom i will be honest i don't really know why this is happening i checked the simple collision that was imported and it seems reasonably tight around the static mesh and everything so it's not clear to me what's going on here but i'm just going to force this to work properly by figuring out how to keep it in the screen on the top and bottom that's a little unsatisfying to me i will freely confess you know i'd like to make this to be perfect but since at this point anyway i only have a single character i can just figure out what this offset is and make it work in my game just fine and although i strongly encourage game developers to try to figure out the cause of every problem that occurs and fix it in the most robust and elegant way possible you've got to understand that there are certainly places in games where you decide that the time or the cost or time is money so the time in cost of chasing down a problem isn't worth it and you just say well i'm gonna fudge it and make it so it works fine obviously horizontally still works fine but vertically she hits the very top of the screen and the very bottom of the screen as well so while i don't encourage people to just put those fudge factors or occludges into their games sometimes to recap in this lecture you learned how to clamp the pawns location so it stays in the screen in this lecture you'll learn how to use action mappings to process mouse button input in your unreal games we'll start with our project from the previous lecture and the first thing we'll do is we'll add the input mapping that we need to process input we go to edit project settings and select input on the left and we have two kinds of input mappings that we use here we have action mappings and we have access mappings so action mappings are for discrete events a button press or a button release something that happens once instantaneously access mappings are used for continuous input like using the wasd keys to control a character or something like that so we don't need access mappings in this lecture though we will need them when we start doing keyboard input but we do need one action mapping we want to destroy our character when the left mouse button is pressed so an action mapping is the correct choice here so i will add an action mapping and sometimes you'll have it show up like this and you'll need to expand with that little left arrow and i'll say destroy character now it's important that you remember exactly what you type here for the name of this action mapping because you're going to need to use it inside the c plus code it is also sometimes the case that it shows up like this when you add it and so you need to expand it and right now there's no key binding to this particular action mapping the way we add a key binding is we click this drop down and we can pick which device we're using in this particular game we're using the mouse and we want the left mouse button so now we've mapped the left mouse button to the destroy character action we've added that action mapping to our game the next thing we do is we add some code to our character player controller script we need to add two functions to the script the first one is the setup input component function which as this comment says is what we use to bind functionality to input to make it so our code can respond to that action mapping the other thing we need to add is a function that destroys the character pawn the function that will actually get executed when that action mapping occurs in our implementation file first we check that our input component field is not a null pointer and we are supposed to automatically get a pointer to a u input component object when we start up our player controller that should be initialized so this is just a safety check to make sure that we did in fact get that pointer if we did get that pointer we want to use our pointer to that u input component object to call remember this notation the arrow notation when we're calling a function from a pointed to object or from a pointer and we want to use the bind action function the first thing we do is we provide the name of the action mapping we're trying to bind behavior to and this is why you need to remember how you actually named that action mapping the next thing we provide is what event on that mapping do we want to respond to so if we look at the e input event enumeration we can see that we can respond to a pressed input event for us on the left mouse button we can respond to it to being pressed we can respond to it being released we can respond to double clicks on it there are a variety of different input events we can respond to on this particular mapping and i know i got really excited when we were spawning teddies to show you how we could use an enumeration when we were setting the spawn location then i admitted we didn't really need the enumeration there but all that stuff that i talked about for enumerations back then applies here for using the enumeration the third argument says this player controller is the one that's going to respond to the action occurring and finally we have to say which function should we call to respond and we don't provide just the function name we actually provide a pointer to the function so we've spent time talking about how variables are stored in memory and we haven't really talked about the fact that functions the executable binary instructions are also stored in memory and so we can provide a pointer to the function and the unreal engine will know to go to that memory address to start executing the function so that's how address of works for functions and so we're telling it if this occurs if the left mouse button is pressed on the action mapping called destroy character the engine should call the destroy character pawn function the destroy character pawn function is pretty straightforward we get a reference to the pawn that is currently possessed by this player controller and we've already seen this code above when we make the pawn follow the mouse on player tick and then once we get access to the character pawn we just tell it to destroy itself and that destroys the pawn that's possessed by the player controller so back in the editor when we run our game we move the character around like we used to but if i press the left mouse button then the character disappears so that's how we can use an action mapping to respond to a discrete input event in our game to recap in this lecture you learned how to use action mappings to process mouse button input in your unreal games last time we finished up with mouse input processing in our unreal games in this lecture we'll learn how to use action and access mappings to process keyboard input in our unreal games we'll start by setting up our input mappings so edit project settings and i've already done it so i've set up one action mapping for a discrete input event pressing the space bar will destroy the minor we have a minor as a character in this particular game and remember axis mappings are for continuous input like for movement and that's how i've set these up so we can move horizontally using the right and left or d and a keys or some combination of those and we can move vertically using up down or ws i want to point out in the horizontal axis mapping that i've set the right key and the d key to have a scale of positive one and i've set the left key and the a key to have a scale of negative one and that's how we'll end up moving to the right on right or d positive along the y axis and how we'll end up moving left when we use left or a going negative on the y axis so this is the setup of the action mapping to destroy the miner like we were destroying our character last time with the left mouse button and axis mapping so we can provide keyboard input as you can see we have our typical game mode that i've customized in the usual way with the pawn and the controller we have a minor pawn and we have a minor player controller for our c plus scripts so let's go take a look at the minor pawn first in the header file for the minor pawn i have some private constants for half collision with and half collision height like we've seen before i did need another kluge factor in height and i just added it into the number there but we need this constant as well we need to know the speed of the pawn how far can it move per frame so this is the speed if we have movement input we didn't need that when we were following the mouse around there was sort of no speed at which we moved we just moved to the mouse location on every frame but here you can think more of we're pushing the miner around with our keyboard input so we have to know how far the miner moves when it has keyboard input and that's what this gives us scrolling past the default stuff we have a move horizontally function that will move the minor horizontally no surprise and move vertically to move the pawn vertically in the implementation file for the pawn we are going to tick every frame and i'm going to move past the tick function and then we'll come back to it so when the move horizontally function gets called what we do is we add a movement input for this pawn we could actually just move the pawn right here but it's a better approach to actually use the movement input system that is in place in unreal so we're going to add a specific movement input we get the actor right vector which is the positive y-axis so we say we want to move along the positive y-axis and we want to move by move scale times move amount per frame now i will say that by getting the positive y vector if move scale is negative we press the left key for example then this will be negative so we'll be applying a negative movement input along the positive y-axis which moves us to the left and we do a similar thing down here with move vertically so if one or both of these functions are called we'll have some movement input that we've added because the functions were called back in the tick function i have an f vector called pending movement input and i call this function called consume movement input vector so what happens is movement input in these functions down here build up a movement input vector that i can consume here to find out if there are any movement inputs waiting to be processed if y isn't zero or z isn't zero that means i have movement input on at least the y-axis or the z-axis i might have it on both but i have it on at least one and i want this if statement because i don't want to do all this work in here unless i'm actually processing movement input so first thing i get the actor location and i put it in an f vector called new location for y i add so now i'm changing the location in y i add the y component of the pending movement input and i clamp on the screen for y for z i add anything that might be pending in z and i clamp in z and then i set the actor location to the new location so this is the pawn having functions called on it saying you should handle movement input and on tick actually processing any pending movement input i should have mentioned when we create a pawn with pawn as the parent class for our c plus plus script we actually get a default function for setting up the input component and i just deleted that i'm not handling any input in the pawn i'm doing all that work in the player controller instead so speaking of the player controller here we are we've seen this function before when we added this function in our mouse button processing so that we could bind to the destroy character action we also have here we want to be able to move horizontally we want to be able to move vertically and we want to be able to destroy the minor so i've added those functions for movement processing and for that action mapping for destroying my minor finally in the minor player controller implementation file i've added my setup input component function and this stuff is new well the assert isn't new right this is just making sure we did get the pointer to the u input component when the player controller was created but this time instead of binding to an action we're binding to an axis the rest of this looks very similar here's the axis mapping name i'm saying this player controller is the one that's going to do it and again we have the address of the function we should call when an input event occurs on that axis mapping in other words if there's some non-zero input on that axis mapping this is the function we call obviously binding to the vertical axis is very similar and this is exactly what we saw before when we were destroying our character by pressing the left mouse button this time i set the input to be the space bar but we're still going to do it on pressed you'll notice this particular argument isn't required when we're binding to an axis because we're just checking for non-zero input we're not trying to determine whether something was pressed or released or double clicked or whatever to move the teddy bear horizontally if the input isn't zero because we only want to do this work if input is not zero we get a reference to our minor pawn and we call that move horizontally function that we already looked at for the minor pawn similarly for move vertically and finally the destroy minor function the body of the function looks much like the destroy character pawn function from our mouse button processing lecture so let's go back to the editor and run the game so i'm going to alt p and now i'm going to try to move my character around and i'm pressing the keys that should move it and it doesn't move and i will confess to you that i spent a stupid amount of time trying to debug my code to figure out why it wouldn't respond to keyboard input and the answer is you have to click in the viewport before your input will work properly so that's something that i'm warning you about you need to click in the viewport so heads up if it doesn't seem to be working click in the viewport and check that might be your problem there is another problem we actually have here though if i alt p again and actually click here i can move my minor around but watch what happens if i press a and d at the same time i can move twice as fast as i move if i only provide input on one of those positive scale inputs for the axis mapping before we fix that problem i realized that i never actually included the move amount per frame in my movement so here and here i'm only adding some number between negative one and one and i intended to also include the movement amount per frame so i'll multiply that number that's between the range negative one to one by move amount per frame in both those places so that changing the move amount per frame will actually change the speed at which i move okay so we've fixed that problem so we can actually tune the speed of movement but we haven't fixed the making sure that we're getting a number between negative one and one there are actually multiple places that we could do that we can do it here we could clamp our pending movement input in y and pending movement input in z to be between negative one and one and that's a reasonable approach to take we could also go down to our move horizontally and move vertically functions and make sure that the move scale parameter is clamped between negative one and one before we add that movement input or we could go to the minor player controller and make sure that when we move horizontally and move vertically that we clamp the input to be between negative one and one before we call the function in the minor pawn so i'm going to say that i don't like the idea of putting it in the player controller because the minor pawn in a good object oriented design the minor pawn if there needs to be some sort of validation of the input or the range of parameters or something the minor pawn should take care of that to make sure that consumers of the class can't screw up the behavior of the minor pawn the minor pawn is responsible for its own behavior so now we're down to the choices of putting it here in these functions or putting it up above in tick when we consume the pending movement input and that's not an arbitrary decision i guess it's a personal choice but i'm going to do it here so before i add the movement input i will say move scale equal fmath clamp and i'll clamp move scale to be between negative 1.0 float and 1.0 float and that way i'm ensuring that when i add movement input the move scale is between negative one and one inclusive and i'll put that here as well and we'll build again to make sure it builds and it does and back in the editor when i run and get focus in the viewport i can go left and i can go right and i'll press right and d and as you can see it doesn't speed up now i will say that there is still a bug in here watch what happens when i move diagonally i can move faster diagonally than i move left and right so that may be hard for you to see but it's true so this is something called the doom strafe 40 bug you can move diagonally faster in fact your speed is whatever the inputs are times square root of 2 and that's just from the pythagorean theorem right so i can move vertically and horizontally but diagonally i'm actually moving further on each frame so i'm not going to solve that problem for you but it can be solved by figuring out your actual complete input vector and normalizing it turning it into a vector of length one and you can do that to get rid of the doom strafe for debug the other thing i should show you is if i am moving around in the screen i can press the space bar and destroy my miner as expected in response to that action and that's how we can use keyboard inputs in our unreal games to recap in this lecture you learned how to use action and axis mappings to process keyboard input in your unreal games i will confess to you that the way i implemented movement with the move amount per frame isn't really a good idea so way back in the old days if you bought a computer video game and your computer happens to have a faster frame rate than the developers used to develop and tune the game then the game ran faster on your computer than the game devs intended if you want to know how to see how to make our movement frame rate independent you should go to the chapter eight of the book that i give you as a reading and you should read about the minor pawn tick function because i walk through how we can actually make our movement frame rate independent in that chapter in this lecture you'll learn how to process gamepad input in your unreal games and lots of people call gamepads controllers that's just fine well you don't need a rubberized controller with hyper responsive buttons and thumb sticks for which you can adjust the resistance i have a friend who may have one of those any gamepad will do the ideas that we'll learn in this lecture will apply to all gamepads the good news is all we have to do is change our input mappings to use a gamepad rather than our keyboard and our game will work the same way except with gamepad input so we can go to edit project settings input and i've already set up the mappings so i have an action mapping called destroy hunter because this time it's a hunter in our game and i picked gamepad face button bottom which is the a button on my xbox controller i also change the mappings for the horizontal and vertical axis mappings so i selected gamepad left thumbstick x axis to move horizontally and gamepad left thumbstick y axis to move vertically and we set the scale to 1 for both of those and it will be negative automatically if we push negatively on the x-axis or the y-axis so now when i run my game i still have to click in the viewport to give it focus before it will respond to my gamepad input but once i do that i can use my gamepad to move left and right and up and down and we get finer grained control with the gamepad with this thumbstick so with keys we were either getting one zero or negative one but with our thumb stick i can push a little and i move more slowly than if i push it all the way and that's one of the benefits of using a gamepad rather than a keyboard we can actually get a range of numbers between negative 1 and positive 1 rather than just negative one zero and positive one and of course i've set it up so pressing the a button will destroy my minor all of the code looks exactly the same as it did before so this is also a benefit of using the action mappings and the axis mappings because we can just change bindings in the editor and we don't have to change any code at all it still works the way it did before and that's how we use a gamepad for input in our unreal game to recap in this lecture you learned how to process gamepad input in your unreal games and we didn't have to make any code changes at all from our keyboard processing game to gamepad processing all we did was did some work in the unreal editor just as a reminder to make your movement independent of frame rate you should use delta time in the tick function of your pawn to make sure no matter what your frame rate is and how it fluctuates your movement works smoothly what will you learn about in this lesson you'll learn about the iteration control structure which is also commonly called looping so you'll learn how to execute a block of code a set number of times and you'll also learn how to execute a block of code until some condition evaluates to false in this lecture you'll learn about the for loop and we use the for loop when we know how many times we need to iterate when we get to the loop as we run our code let's go take a look the for loop will write will print the squares from 1 to 10. so we type 4 and we put open and close parenthesis and we have two semicolons here and then we'll put the body of the for loop and just as with if statements if we only have one statement as the body of the for loop we can omit those curly braces but i always suggest that you include them we have two semicolons up here because we have three parts to our for loop we initialize something that i'll call a loop control variable because this variable i will control the execution of the loop the next piece that we have is some condition that will test every time we get to the top of the for loop we'll test this condition to see if it's true and if it's true we'll go into the body of the for loop again and if it's false we'll go past this closed curly brace and move on in our code so my condition here will be i less than or equal to 10. and you should recognize this as a boolean expression right this will evaluate to true or false and then finally i need to say how i'm going to modify the variable that controls the loop the loop control variable as i'll call it and i will modify this by incrementing it so plus plus is the increment operator and so if i is zero i plus plus is one if i is one i plus plus is two and so on in here all i need to do is print out the square of i one per line so i'll use standard c out and i will print i times i and i know i'm going to want a new line as well so now i can run my code and it prints out the squares from 0 to 10 because i set i to 0 here not 1 so let's try that again i want to start i l1 so i'll run it again and i get the squares of the numbers from 1 to 10. now the way this works is the first time through the loop we set i to 1 and we check if 1 is less than or equal to 10 and of course it is so i go into the body of the loop and i print out one times one now i come back to the top again because i finished with the body of the for loop and the first thing i do is i increment i so now i is two two is less than or equal to 10 so i go into the body of the loop and i print out 2 times 2 i come back and make i 3 and we keep doing this until we increment i and i becomes 11. when i becomes 11 11 is not less than or equal to 10. so we break out of the for loop we don't execute the body anymore we just move past it to this line of code which happens to be the end of our main function now you might see people using different formats for the for loop for example you could take this part and put it here instead and everything will run fine as you can see the reason you might do that is because if we do it this way which is the most common format for a for loop this i is declared here so it's only visible here so that is the scope it's called the scope of i it's where that variable i is visible and that works fine for most for loops but if you need access to i out here on line 17 i is no longer visible so you couldn't use it so that would be one reason that you might put your loop control variable declaration and initialization before the for loop you might also see people doing this and just incrementing i here instead that's probably less common but that also works and finally you're likely to see people doing this instead of i plus plus and that also works fine as you can see there are some subtle differences between this and this but they don't matter in this particular case but there are other cases in c plus plus where the place you put the plus plus actually matters we're not going to deal with any of those cases in any of the courses in the specialization but you should understand that plus plus i also increments i okay so this is interesting right but let's actually make it so that the user can provide how many squares they want so remember in the intro i said that a for loop is useful when we know how many times we're going to loop when we get to the code that's not the same as saying we know how many times we're going to loop at compile time so we can prompt for and get how many squares to print so we'll start with the prompt and i'll just say enter how many squares to print and i'll give the user a hint about what they should use as the range but they can ignore us as we'll see soon and now we're going to read in how many squares to print and by now i mean after i declare the variable that actually will hold that number so we'll read into n and we'll say here we're going to print the squares from 1 to n and we'll change our upper bounds to n instead of 10. so now when we run we can say how many squares to print and we can say 10 and it prints the squares of the numbers from 1 to 10. we could say 3 and it prints those squares as well if we do something like this if we say print 0 it doesn't print any so here's how that works if we read into n and we get to line 18 here and we set i equal to one but then we check to see if one is less than or equal to zero and one is not less than or equal to zero so we don't ever execute the body of the loop and we just move on to this blank line after the for loop so that's how you can use for loops in c plus plus to recap in this lecture we learned how to use a for loop to execute a set of statements the loop body a certain number of times last time we learned how to use four loops to execute a chunk of code a set number of times this time we'll learn how to use nested for loops so to build the nested for loops we just put one for loop inside another what are they good for in general they're good for traversing two dimensional or higher dimensions of data to demonstrate nested for loops i'm going to print out the multiplication table for the numbers from 1 to 10. so the first thing we'll do is we'll print the header for that table it will become clear to you momentarily why i'm starting by printing five spaces now i'm going to use a for loop to print the numbers from 1 to 10. and this isn't the nested for loop stuff this is just a regular for loop and i'm going to do things just a little differently here because in a table i want each output to be in a field if you will of a particular width and i know how to do that in c plus we can just use set width and say how many characters that field is going to be and then i can print out i in a field of width 5. i'll point out that set with is in the i o manip i o manipulation library so you need to pound include that library if you want to use set with but now we can run the code to show that our header appears properly with that space at the beginning the reason i want that space in the beginning is because when i print the table i'll show you where i needed that space so here's the nested for loop stuff my outer loop i will set my loop control variable and i could call this anything it doesn't have to be i it could be row or bob or joe or whatever it's fairly common to use i as a loop control variable here so i'm going to do that and i also want to point out that this eye is not the same as this eye remember we talked about the scope of this eye up here and it's from here to here so the scope of this i is from here to here and it's a totally separate variable even though it has the same name the reason i wanted to print out those first five spaces at the beginning of the table header is because i know that here i want to print out i and i will also say that i need to put standard there and i will also say that here right before i loop back in this outer loop we don't have the inner loop yet but before i loop back i know i'm also going to want to print a new line and if i run my code now i realize that the one that i wanted on the left is at the end of the editor so i will print a new line here as well try that one more time so there you go i have the header along the top and each row will be the you know we do row times column to do our multiplication table so now all i'm missing is that inner loop i'll do another for loop and i can pick any variable name i want except i if i pick i here it's going to screw everything up because this i here is visible from here to here so it's really common to say j equal one j less than or equal to ten j plus plus and in the body of this inner loop i will print out in a width of five the product of i times j and of course i need two colons there push that back where it belongs and now when we run our code we get the entire multiplication table and you can convince yourself that this is correct but each cell is the product of its row and its column so how does this work when we get to the outer loop the very first time we've just printed the header we set i to 1 and we know 1 is less than or equal to 10 so we go inside the body of that loop we print out i and now we get to this loop so we set j to 1 one is less than ten so we print out i which is one right now times j which is also one right now and then we get to the end of this inner loop and we come back to the top and we set j equal to 2 2 is less than or equal to 10 so we print out 1 times 2 which is 2 and so on so this inner for loop works just like a for loop like we learned last time now when this for loop ends we've just finished printing a row of the table so we move to the next line and now we get to the end of the outer for loop we increment i from one to two and then we come into the body again and we print out two and here's where people sometimes get confused so when we get to this inner loop again it has no memory that it has ever executed before so we initialize j to 1 and do that in our for loop so it's sort of like wheels spinning within wheels right we get to the outer for loop and then we spin the inner for loop till it's done and then we rotate the outer for loop one tick and then we spin the inner for loop again and then we rotate and spin and so on so the important idea is the inner for loop always starts fresh whenever we get to it and it works just like a for loop and the outer for loop also works just like the for loops we've learned before and that's how you use nested for loops in c plus plus to recap in this lecture you learned how to use nested for loops to do something useful last time we finished our discussion of for loops in this lecture we'll look at while loops which help us solve problems where we don't know how many times we're going to need to iterate when we get to the loop one of the places that people regularly use while loops is for something called input validation we're going to have the user input some data for us and we need to validate or make sure that it's within a particular range or a specific format or something like that we're going to do input within a particular range in this lecture so what we're going to do is we're going to have the user enter a test score so prompt4 and get score and of course before i do that i'll actually need a variable to hold the score first we'll prompt and if we have an expectation that the user input will be within a particular range we should tell the user what that range is and then we'll read it here's the while loop part we put the while keyword and we put parentheses and we put curly braces and of course as always if the body of the while loop is only one line of code you can omit the curly braces but i suggest you always include them and in between these parentheses we put a boolean expression and the way while loops work is if the boolean expression evaluates to true we're going to go into the body of the while loop so the boolean expression we need to specify here needs to be an invalid test score that's the only reason we're going to want to loop to ask for a new input from the user so this may seem counter-intuitive to you but we need to write a boolean expression for an invalid score an invalid score is either less than zero or it's greater than a hundred any score that's between zero and a hundred inclusive is valid so for those scores this boolean expression will evaluate to false but for invalid scores this will evaluate to true so we should print an error message and get a new score so first we'll print an error message score needs to be between 0 and 100 and then we prompt for and get the score just like we did above so let's see how this works if i enter a valid score we're all done so that tells us that the body of a while loop executes zero or more times we entered 100 up here and this boolean expression evaluated to false so we immediately went to the line after the while loop body of course the zero or more times i can make it execute more than zero times so here's an invalid score and it looks like i need some line breaks but now i'll enter a valid score and everything's okay so let me put some line breaks in here one to offset the error message from the user input they just provided and of course one here as well we'll just test to make sure i did that properly so negative five five and we're good the reason we're using a while loop here is because we don't know how many times the user is actually going to provide invalid input so we can't use a for loop right we don't know what the limit is for how many times the user will either be confused or malicious so it will just keep looping with invalid inputs as long as the user keeps entering invalid inputs and then finally when they finally enter a valid one we'll break out of that loop because the boolean expression evaluates to false i'm going to add one more comment here and i also want to mention that people will sometimes talk about getting stuck in an infinite loop the for loop is not as prone to infinite loops you can build an infinite loop if you choose to with a for loop but people usually end up with infinite loops by mistake i will point out that there will be times as you look at code that you'll see somebody do something like this they'll say while true which is by definition an infinite loop until they put some code inside here to break out of the loop when you should break out of the loop there are certainly places where that structure is appropriate but certainly not in input validation we should just do it a more reasonable way like this but people can get into infinite loops and there are three things we need to think about when we are trying to avoid infinite loops for our while loops and the initials for those things are i t m and itm stands for initialize test and modify so let's talk about them one at a time first of all before we get to our while loop we need to make sure that we have initialized our loop control variable to a reasonable value now it turns out that we could have multiple loop control variables for a while loop and that's fine we should make sure they're all properly initialized before we get to the loop in this particular example we've initialized score before we get here so we don't need to worry about that particular issue the next one is test so we need to make sure that this boolean expression that we write is correct but let's say we got confused as we were writing this boolean expression and we said while score is greater than zero or score is less than a hundred we got our relational operators incorrect when we run the code i can enter any number i want and it gives me an error message and that's true of invalid numbers and more invalid numbers and you say oh i'll take a 50. you're just stuck in this infinite loop forever the problem is that you can't think of a score that is neither greater than 0 nor less than 100 and some scores are both right any score that's 1 to 99 will meet both of these criteria for the or but all numbers meet at least one so that's an example of getting the test incorrect and ending up in an infinite loop and that last initial m for modify tells us that we need to be sure to modify at least one of the loop control variables that we have controlling our loop which we're doing with this line of code but if we forgot that line of code and we were in our code i'll have to enter an invalid score to push us into the body of the while loop the first time but then i go forever so let's talk about how this works if this boolean expression evaluates to true i go into the body of the while loop and i do this stuff and i never change score so when i loop back around to the top to check the boolean expression again it's still true because i never change score so i go to the body and loop back around and it's still true and so on so i'm going to fix this so those are ways that we can end up with an infinite loop now it's not really infinite right at some point you'll rage throw your computer against the wall or the sun will explode or something they're not actually infinite but the while loop doesn't actually behave properly in terms of how many times it iterates to recap in this lecture you learned how to use while loops to solve problems where we don't know how many times we'll need to iterate when we get to the loop you learned that the body of the while loop executes zero or more times and you learned that thinking about initialize test and modify helps you avoid writing infinite loops last time we learned how to use while loops to solve problems where we don't know how many times we're going to iterate when we get to the loop this time we'll look at do while loops another way to solve those problems we'll start with our while loop code from before though i did change the comment up here so we'll just reformat this to use a do while loop instead the big idea is we put the keywords due and then we have curly braces and then we say while some boolean expression and the boolean expression we'll use i'm going to beat visual studio into submission the boolean expression we use is identical to the boolean expression we used before so we format it like this and we'll prompt for and get a score inside the do while loop so because we start at the top and work our way down the body of a do while loop executes one or more times there's no way to skip the body of a do while loop because we don't get to the condition until the end and so far this feels like a win because we can do this we can run our code and we can't actually run our code because i left all the stuff here hanging around so let me just comment out all this code right here but we can run our code now and as you can see if i enter 100 i'm all done if i enter an invalid number i get another prompt i'm looping through the body of the loop again and i can enter another invalid number and i'm still looping and then finally i stop looping so we're missing a piece though here we're missing the error message that tells the user they did something wrong and we really need to include that so we need this print error message part that we had before but we only want to print it if what we just read from the user is invalid so we need to add an if statement here that uses the same boolean expression as the while condition for the do while loop and then we can print that error message and i won't say and get new score i'll say as appropriate and in fact i'll put that comment here instead and now if i run the code from the user's perspective we'll see that this looks just like a while loop implementation the user has no way of knowing how we actually implemented this loop and i'm going to get rid of all this dead code that i don't need anymore so when should you use a do while loop well you'll certainly hear people argue that if you need to execute the body of the loop at least once the do-while loop is the correct loop to use and in particular for input validation but for lots of other scenarios as well here's where the do while loop wins we know we have to do this once and we only need to include this code one time here at the top of the do while loop in case you've forgotten in the while loop we had this code before the while loop and we included this code in the body of the while loop when we were getting a new input after we printed the error message so our while loop duplicated these lines of code twice and here we only need it once the downside is we also need to include an if statement if we're going to print out an error message so we've saved some duplicated lines of code but we've added some complexity overall to our code because now we don't just have the iteration control structure we have the iteration control structure in the selection control structure in our code to get the same functional behavior this is really a matter of personal preference i will say that i personally never use do while loops i always use while loops because they are less complex even though i end up with a little duplicated code but you can decide whether or not you want to use do while loops in those situations where you know the body of the loop has to execute at least once to recap in this lecture you learned how to use do-while loops to solve problems where we don't know how many times to iterate when we get to the loop we learned that the body of a do-while loop executes one or more times and we also learned that sometimes using a do while loop leads to more complex code than using a while loop last time we finished talking about the three different kinds of loops that we commonly use in c plus plus that's a little lie because we'll learn about another variant of the for loop in the next lesson but it's good enough for now in this lecture we'll learn how to use lots of what we've learned in this lesson to solve a particular problem here's the problem we're going to solve we need to build a box with asterisks all around the edges of the box using a user specified width and height the constraints on this problem are that both the width and height needs to be between 3 and 20 inclusive let's go solve that problem this is a really interesting problem because it lets us use while loops and regular for loops and nested for loops so it's a great problem the idea for this problem comes from beginning c a book by ivor horton and i know i'm teaching you c plus plus here but this is a great book to use if you want to learn how to program in c and i took the idea for this problem from that book okay so my starting code i have variables for the width and height of the box and then i have while loops to do input validation to make sure i get a box width that's between 3 and 20 inclusive and a box height that's between 3 and 20 inclusive i will freely admit to you that i wrote my input validation for the with and tested it and then i copied this code and i pasted it down here and i changed width to height and as a programmer that made me feel really sad that's a horrible thing to do copying and pasting is never the right idea if you need the same code what i really wanted was to write a function that would get me a value that was between a lower bound and an upper bound unfortunately we haven't really talked about writing our own functions yet so we're not ready to do that yet so i did it the same way that you would probably have done it but i found it very unsatisfying to do it that way and once we know about functions you'd absolutely write your own function okay so how do we print out this box well the first thing we're going to need to do is we're going to need to print out the top row of the box which is really just a solid line of asterisks that's the user specified with we know how to do something a particular number of times that's definitely a for loop and we can start i at 1 and we'll go for the full width so i less than or equal to it and we'll increment and the only thing we need to do in here is print out a single asterisk and once the loop is done we'll want to print out a new line so that we can move off that top row so let's test this it doesn't matter what i enter for height but if i enter a reasonable width you'll see i print five asterisks as the top row again feeling like a bad programmer i'm going to print the bottom row by copying and pasting that top row stuff and i can test that and if i enter some valid width and some valid height you'll see i have the top and bottom rows of the box the most interesting part of this problem is print the middle of the box so we need to think about how many times we're going to do this first of all how many rows are there in the middle because that's a good for loop for us so i'm going to actually start i at the second row and how many total rows do we print in the middle we print height minus two so height minus the top row minus the bottom row we can specify our condition here in a variety of different ways but i'm thinking of i in this loop as keeping track of which row we're printing so we start by printing row two and then we're going to print all the way up to row height minus one so i'm going to say i less than or equal to height minus one now i know that implies we always need to use a less than or equal to here i could just as easily have said i less than height but i find this more readable thinking of i as the actual row number i'm printing here i am going to increment i and now we need to think of what does a particular row look like and a particular row looks like an asterisk and then a bunch of spaces and then an asterisk and then a new line so let's do the asterisks at the end first and of course i'll do the new line as well and let's go ahead and do this i know it's not going to be correct but let's watch all those rows print without the spaces in the middle so i'll run the code and i'll say the width is five and i'll say seven rows and there you go i have the top row and i have the five middle rows even though we're just doing the asterisks and then i have the bottom row so now we need to add the spaces in between i'll need another for loop for this because i don't know at compile time how many spaces i need but i will say that i'll think of this the same way as i did the outer loop i'll think of j as being the column i'm printing in so i know that i'll start j at 2 and i'll print while j is less than or equal to width minus 1 and i'll increment j and here what i'm outputting is a space so now i'll test my code again and i'll say six by six and there's my nice six by six box i will point out of course i was printing out strings up here but as i'm printing out characters i can print out character literals as well so it doesn't have to be strings when i'm printing out a single character but i'll show you we get exactly the same output if we print out asterisk characters and space characters let's do a big box 20 by 20 and you can pause the video and check to make sure but i promise you that's 20 by 20. and i'll show you a three by three box our smallest possible box so as i said this is a really interesting problem to solve we have regular for loops we have nested for loops and we have while loops to recap in this lecture you learned how to use while loops and for loops and a nested for loop to solve an interesting problem and i know i mentioned ivor horton's c book but horton also has an awesome beginning c plus 17 book if you'd like to dig deeper into c plus in this lecture we'll use what we've learned about for loops to spawn multiple teddy bears each time our spawn timer goes off we'll start by adding a constant to the header file for our teddy bear spawner and our constant will be for how many teddy bears to spawn each time so obviously this will be an int i'll call it teddy bears per spawn and why don't we set it to something like 10 to start with so every time the spawn timer goes off we'll spawn 10 teddy bears instead of one over in our implementation file all we need to do is we've got this block of code in our spawn teddy bear function that randomly picks a teddy bear to spawn generates that random spawn location and then spawns the teddy bear so we can just do this repeatedly we can say for int i equals zero i less than teddy bears per spawn i plus plus and we'll put all this work except starting the timer again into the body that for loop i'm going to compile and i've compiled successfully so back in the editor i run my game and then we get a bunch of teddy bears spawned in there and so on and we're doing 10 at a time this is awesome and of course we're getting a big pile of teddy bears and they're dying off a little bit at a time and that's how we can use a for loop to spawn multiple teddy bears each time the spawn timer goes off let's actually spawn even more each time the spawn timer goes off and i can do that by simply changing how many teddy bears i do per spawn to a hundred and when i run the game now and isn't that awesome now it turns out that some of these teddy bears i better stop this it turns out that some of these teddy bears are actually spawning into collisions and we may want to control that we may not want to spawn a teddy bear into a collision with another teddy bear especially because these are physical objects that collide with each other and the way we can do this is we can select each blueprint and just search on collision and you can see that this spawn collision handling method controls how we're going to handle this if we're spawning this actor into a collision so by default this is set to always spawn ignore collisions we can let the engine try to adjust the location so it tries to find a nearby non-colliding location but it will always spawn even if it can't find such a location we can try to adjust the location and not spawn unless it finds a non-colliding location or we can say never spawn we don't want that one but let's try to do this one we'll try to adjust the location and don't spawn if it can't find a non-colliding location that will mean that we don't spawn as many objects as we thought we would but this is potentially better than spawning into a physical collision with another object that has physics behavior and we compile and save and we're going to do that for all of our blueprints that were spawning into the game so now when we run our game we got lots of teddy bears but we didn't get a hundred because it was unable to find spawn locations that were not colliding so if you want to be safe and spawn multiple things or even when you're spawning just one thing into your map to make sure it doesn't spawn into a collision you can adjust the behavior of the spawning for that particular actor as it's getting spawning to meet your particular collision free needs and that's how we can use a for loop to spawn multiple teddy bears into our map each time the spawn timer goes off to recap in this lecture we used a for loop to spawn multiple teddy bears each time our spawn timer went off what will you learn about in this lesson you learn how to store multiple values in a single array variable you'll learn how to process arrays using for loops you'll learn about the c plus array and vector containers you'll learn about the unreal t array container and we'll look at a ted the collector game together the big idea behind arrays is that arrays let us efficiently store multiple values in a single variable so what can we store in arrays we can store anything but each array can only store one data type so we can have an array of ins and we can have an another array of actors but we can't mix ins and actors in a single array this is a conceptual representation of what an array looks like so typically we will declare an array as a variable and i have declared this array as a variable named gpas now each of those boxes that contain 0.0 is actually a location in memory and the separate things that are stored in those locations in memory have a specific name and that name is elements so we talk about the elements of the array as the contents of the array now in this particular array we have elements that are numbered 0 through 9 and we'll talk in a couple of lectures about why we start at zero but those numbers on the left hand side give us a way of indicating which element we want to do something with we might want to find out its value we might want to put a value into it but we need a way to say within this gpas variable of 10 elements which element we want to do something with the number that we use to access a particular element in the array is called an index we'll start by declaring our array variable and the first thing we put is the data type for each of the elements in the array then we put the name of the variable and i'm going to store some test scores in this variable and this all looks just like the variable declarations we've had so far the way we tell the compiler that we're going to actually have an array here is we put square brackets and we also put how many elements we're going to have in the array and once we've declared an array we can't change the size of the array the way we actually access elements in the array is we put the array name and then we use square brackets and we provide the index of the element we want to manipulate and then we can do something like set scores zero to a hundred we start our indexing at zero remember and we can do this as well and so on but this doesn't really actually harness the power of the array so much because if we just do a line of code for each element and so on this is going to be pretty awkward especially for larger arrays so one of the great things about arrays is we can actually walk the array or touch each element of the array using a for loop so i'm going to comment this out and instead of doing it that way i'm going to use a for loop we're going to start our loop control variable at zero we're going to run our loop control variable up to but not including 5 because remember our elements are numbered 0 1 2 3 and 4 for this particular array and we'll increment i each time through the loop i'm going to use this for loop to read in the scores and what i'll put in the body of the loop is our typical input validation code so i'll go do that and then we'll come back and talk some more so here we are we're going to prompt for and get a score and i've done a couple of things differently from what we've done before so i'm telling the user which score they're entering and i'm using i plus one because the user is a human not a c plus plus programmer so humans start counting at one so we'll be asking for test scores one through five but we'll be putting them at elements zero through four and the other difference is here where i'm reading into a particular element of the scores array so we saw up here that i can use literals to access particular elements of the array but i can also use variables because variables hold a value and that value will be the index we use for the element in our array and the rest of this is what we've seen before of course checking for invalid particular elements that we've just read into rather than just a single variable like we've done previously okay let's run this code and i'll show you that the input validation loop works properly and then i'll just enter some scores like so so that's how we can use a for loop to actually populate the array let's print out those scores to make sure we actually populated the array properly and you might think that you can do something like this and this will certainly compile but when we run it you'll see that you actually do not get the elements of the array there we're actually looking at the memory address of where the scores array is stored so that's not really what we wanted to do we can't just print out the array all at once we actually need to use a for loop to print out each element of the array i know i'm going to want a line break before i do this and now we need a for loop again and of course we want to print out scores i and there you go now i will point out that we've been hard coding the size of the array in these for loops and we'll actually learn a better way to do that but not in this lecture because this lecture was to give you your first introduction to how arrays work in c plus to recap arrays let us store multiple values in a single variable but we know those values have to all be the same data type we also learned that once we create an array we can't change the size of the array and i will comment that i inadvertently started some of my variable names with the lowercase letters in the videos but i've fixed that in the code that i'm providing to you in the previous lecture we learned how to declare and use an array to store multiple pieces of data this time we'll look at various ways we can initialize the elements of the array our starting point is code that declares a scores variable an array of five integer scores and then a for loop that prints out the values of each of those scores we have a warning here that says that we're using uninitialized memory so we're going to get whatever we get in those memory locations in fact if i run the code you can see i get a whole bunch of negative numbers here that's just the garbage that's sitting in memory when the runtime system goes and grabs five contiguous pieces of memory for holding five ins it just gets whatever is there we do know from the previous lecture that we can initialize an array by getting user input and we'll actually learn later that we can also initialize an array by reading from a file and putting values from the file into the array but in this lecture we're going to explore initializing the array using a braced initializer so i can say i want specific elements in the array like this and i can get rid of the five when i do that and you of course and of course i'll need a semicolon and now when i run the code you can see that all the elements of the array have been initialized to zero i can also set each of those scores to a different number like so so they don't all have to be the same and as you can see those scores have been populated into the array properly now you might be wondering why don't i need to provide a number here and the answer is easy it's because the compiler can figure out if you've provided five values for elements in the array then you want an array that has five elements in it back to initializing things to zero if i want all the elements to have the same value i can just provide that value if i do i need to come back here and say how big do i want the array to be because the compiler can't figure out from one value how many you want it to be as you can see this works perfectly fine when i run it if you forget to do this here's what happens the compiler decides to give you an array of one element and it initializes that element to zero but what are these other scores we're actually just walking along through memory these last four values aren't part of the array they're just whatever happens to be sitting in memory at those locations past the end of the array this is really dangerous in c plus plus we can just walk past the end of the array and we are walking through memory and we think we're still in the array but we're not we'll learn a safer way to do this before we're done with this lesson but it's important to realize that that can happen so we'll make sure if we're going to initialize a bunch of elements in the array to a particular value to specify the array size here when we do that and just confirming that that works fine so there are a whole variety of ways we can use a braced initializer to initialize the elements in our array to recap in this lecture we saw various ways we can initialize the elements in an array last time we learned a number of different ways we can initialize the elements of our array this time we'll see why we start indexing our arrays at zero i've done some preliminary work here to set us up for this discussion i've declared a scores array that has these values in it and then i'm using a for loop to print out information about the array i'm going to print out scores i a label that shows us which element we're looking at and i'm just going to use i not i plus 1 because we're programmers here so we want it to start at zero i'm going to print out the address of that element in the array and i use standard hex to say i want to print out what comes next in what's called hexadecimal or b16 and we'll see that as soon as we look at the output and i'm going to print out the address of the element in the array not the element in the array not the contents i'm printing out an address here this is the address of operator which we've seen before then i'll print out the actual contents telling it i want it back in decimal or integer form and this will be the contents of that element so i'll label the scores i'll print out the address of that location in memory and then i'll print out what's contained in that location in memory okay let's go ahead and run the code okay so here we see score 0 is at this address and this is hexadecimal this is base 16 so each place in our address is 0 through f so 0 through 9 and then a b c d e f are the possibilities for each place in this address so the array starts at this location that ends in 4 and here's the contents and then we walk down and this one's at 8 and this one's at c and this one's at 0 and 4. so why are these offset by 4 each time 8 plus 4 is c in hexadecimal the reason is that we said that we want this to be an array of integers and integers take up 4 bytes so if we start the array at location bunch of stuff 4 then we need the first element of the array to have the spaces in bytes 4 5 6 and 7. and then we can put the next element of the array at 8 and the 4 bytes we need here are 8 9 a and b and so the next element at scores 2 goes at c so that sort of explains why the memory is laid out the way it is for this array arrays are always in contiguous or next to each other pieces of memory but that doesn't explain why we start at zero the reason we start at zero is for efficiency so we have this base address of the array ending at four for score zero and the way we calculate the memory address for an element of the array is we take the base address and we add the index multiplied by the size of each element in the array so if we want to access score 0 we take the base address and we add 0 the index times 4 the size of each element in the array so we add 0 so we end up with the base address which is exactly correct if we're trying to access the element at index 1 we take the base address and we add the index 1 times the size of the elements four so we take four this address that ends in four and we add four to it and we get eight and just doing one more if we're trying to access element two we take the base address and we add two times four so we add eight and four plus eight in hex is c so we've accessed the element at index two so that's why we start at zero it's a base address plus the index times the size of each element in the array and the computer can calculate that very quickly if we started at one there'd have to be a subtraction every single time to say the index you're trying to access minus 1 times the element size and so there's no reason to do an extra subtraction every time we access an element of an array so if we start at 0 we can avoid that subtraction and it's more efficient to recap in this lecture you learned that we start indexing our arrays at zero because the index is used to calculate and offset from the base address of the array in the previous lecture you learned why we start indexing our arrays at zero in this lecture you'll learn several ways to determine the size of an array at runtime i've already generated all the code we're going to use in this lecture so we're just going to talk about it one way we can find out the size of an array that we've declared is by using standard size so you could look at this and say well i know the size of the array i can see it right here but sometimes the places that we're using the size of the array are actually far away from the declaration of the array itself so this is a good way to determine at run time when you're about to use the size of an array what the size of the array is we have this function called size and we can hand it an array and it will tell us how many elements the array has so we'll look at the first line of output when we run this code and as you can see in that first line of output it says we have three array elements which is of course correct because we've declared an array of size three if your compiler doesn't support using size which was added in c plus plus 17 there's another way to do this and the way you can do this is first of all you can use size of for the entire array notice this isn't standard size this is size of and this will tell you how many bytes the entire array takes up in memory you can then get the number of bytes for one element in that array and i often just do the zeroth element assuming i have an array of at least one element so this tells us how many bytes a single element of the array takes and if we know how much space the entire array takes and how much space a single element takes then we can calculate the number of array elements by taking the entire array size let's say 12 in this case because it's three integers and dividing by the size of a single element which is four in this case and that will give us the number of array elements that we have i'll run the code again and as you can see 12 bytes for a three element array of ins each element takes four bytes because it's an int and then we divide 12 by 4 and we get 3. so those are two different ways to get the size of an array at runtime remember we can't change the size of the array after we've declared it so it this scores array will always be three and it's also the case even though you might want to do it it's also the case that the c plus plus standard does not let us dynamically figure out how large the array will be in other words we can't ask the user how many scores do you want to enter and then declare an array of that variable size the compiler has to be able to figure out at compile time how big the array will be now there are numerous compilers that will let you actually do it even though it's not in compliance with the standard but i'm not going to teach you those ways because i want to only talk about c plus standard code so we can figure out the size of the array in multiple ways and then we can read in the scores this is acting like there's an error here but if i compile this is up to date so let me clean the solution and compile again so if i compile you'll see that it compiles fine so you can ignore those red squigglies there are a couple of warnings that we will come back and take a look at but first i want to talk about how we can read in the scores so our typical for loop but instead of our hard-coded size here and i will also say that we could have declared a constant for the size of the array and then just use this constant here i know i hard-coded five in examples in previous lectures and that was probably the worst of all worlds but i wanted you to sort of see how we can walk an array to manipulate particular elements of the array but this is a good best practice to access the size of scores before running the for loop over the scores array this is all code you've seen before here in the inside so this is the difference from what we did before we can also print out the test scores using this as our upper bound so i'll run the code yet again and i'll enter three scores and it prints out what those scores are i said we could talk about those warnings and i'll need to clean and build again to see them and those warnings say on line 28 and line 50 that we have a signed and unsigned mismatch using the less than relational operator what that means is we've declared our loop control variable to be an int which is a signed integer can be negative zero or positive the size function however returns an unsigned integer so the warning is you're comparing a signed value i right here to an unsigned value the return value from this function we can actually use size t which is defined as some form of unsigned integer we don't know whether it's unsigned into or unsigned long or unsigned long long we can just use size t and size t is an unsigned integer data type and size t is used a lot in the standard library for sizes of things like we see here and counts of things so we will find ourselves at least sometimes using size t as the data type for our loop control variable in our for loops when we're dealing with sizes of things i'm going to change both of these and i will also say that we haven't spent much time talking about warnings they're warnings right they're not errors so your code will run but many programmers want what are called clean compiles no warnings no errors everything is as high quality as possible so i felt compelled to get rid of those two warnings if i built again you'll see those warnings have gone away and i'll also demonstrate that the code still works the way it worked before so even though this lecture was focused on figuring out how big an array is at runtime we got to learn some other stuff about size t as well to recap in this lecture you learned a number of different ways to determine the size of an array at runtime the standard size function became available in c plus plus 17 so if you're in a c plus 17 environment you should just use standard size but if that's not available to you i also showed you how you can use the sizeof function to determine the size of the array if you're working in xcode you need to configure your xcode project to use c plus 17 and i've provided a reading showing you how to do that in the lecture resources for this lecture in this lecture we'll process the data in an array to calculate the average of the elements in the array as usual we have an array of scores although i keep changing the number of scores we're going to use so this time we'll have four scores that we're processing we'll first read in those scores and we're using that size function that we've talked about and i've declared i to be of type size t because i hate warnings here's our standard input validation stuff and now we're going to walk the array and calculate the average so i initialize a sum to zero i do another for loop here again using size and using size t and each time through the loop i add scores i to the sum and this plus equal is identical to this but it's a convenient shorthand so many programmers just use plus equal if we're adding something to some here and of course we get minus equal and divide equal and times equal and so on so this for loop adds up all the values in our scores array and then i declare an average variable that is of type float and i typecast the sum to float so that i do floating point division here not integer division and i divide by how many elements there are in the array and of course if we add up all those elements and divide by how many there are that is by definition the average finally i do one more for loop and i walk through the elements in the array and print out the value of each element and then i print out the average as well as you did in programming assignment 2 we're going to set our precision for our average output to be two decimal places if our average doesn't have any decimal places or if it only has one then it will print none or one but if it has more than two decimal places then this will be rounded to be two decimal places so i'll run the code and i'll show you an average with no decimal places and as you can see it prints an average with just the whole number because that's all the average has i can show with one decimal place you can see it's 2.5 so these are standard ways that we've seen that we process an array whether we're populating the array with values provided by the user or we're printing out the contents of an array or we're walking the array to do some processing i said back in the iteration lectures that i told you a small lie that there was another variant of the for loop that we can use that i hadn't shown you yet and i want to show that to you now because we very commonly use it when we're processing arrays this variant of the for loop is called a range-based for loop so instead of doing this we can do this we can say int score and provide a range of values to walk across so let me fix line 36 and then we'll come back to that so here's the idea we have a range that we want to iterate over remember the looping is the iteration control structure and instead of having to index into the array each time on line 36 we provide a variable that will get populated each time we go through the loop with a different element of scores so the first time through the loop score will be set to scores 0 and so down here we will add scores 0 to our sum when we come back to the top of the for loop again score gets set to scores one and we go through and do some stuff until we've walked the entire scores array notice we don't have to calculate the size of that scores array or anything the system knows that scores has four elements and so this for loop will execute four times and as that happens the first time through score will be score zero then scores one then scores two then scores three and then the loop will stop i'm going to run the code to show you that this works the same way and as you can see it works exactly the same way so the range base for loop is a very powerful variant of the for loop that we regularly use when we need to iterate over a range of values like an array of values you'll notice though i could try to do that here as well but will actually have a problem because i'm using i inside the body of the for loop in a range base for loop we don't get i we don't know which iteration we're on in the body of the for loop if we don't care like we didn't when we were adding up the values of all the elements then we should use a range base for loop but if we do care like we do when we want to label our output to tell the user which score we're displaying then we need to use a for loop that uses the loop control variable as shown here similarly when we're reading in the scores we're actually telling the user which score they're entering so a range based for loop isn't appropriate in this scenario now if you want to provide less helpful output to the user you could use a range based for loop but it's really best to give the most helpful output to the user and use range based for loops when they're appropriate and they are appropriate many times to recap in this lecture you learned how to process the data in nnri and you also learned about the range-based for loop in this lecture we'll look at the c plus array container which is a good alternative to using the arrays we've been discussing so far in this lesson our starting code for this lecture is the code from the previous lecture where we were using arrays in this lecture we're going to convert this code to use the array container instead the array container is something called a class template so we've learned about classes before but a class template means that we're going to provide some template parameters and we'll end up with a concrete type based on those template parameters we've provided so we'll convert the scores array to an array container instead so i'm going to say here standard array and i put my template parameters between less than and greater than and the two template parameters that i provide are the data type of the elements in the container so that's int and i still need to provide a size that the compiler knows about at compile time so even though i'm using this array container i still have the constraint that i had with arrays that i can't dynamically size them i have to say what size it will be at compile time so i'll make it four and i get rid of that notation at the end and we'll see if i compile that scores uses an undefined class because if i'm going to use the array container i need to pound include array and once i do that i can compile again and the build succeeded i'll run the code to show that it works the same way it did before and you might be saying well that's not really a win yet and that's true we haven't actually seen the win yet but we'll see it soon one of the things we can do with the array container is actually access the size function of the array container rather than using standard size here so i can treat scores like an object like we've done before so i can actually call scores dot size to access the size of the score's container and i'll just change that every other place this appears which is here and here now you'll notice by the way that i still used a range-based for loop here to walk the contents of the container so containers also have an iterator we can iterate across them using the range based for loop so i can keep doing that as well here's one of the huge wins for using an array container rather than using an array so here we are printing out the scores and if we make a mistake here if i say less than or equal to rather than less than now remember from our previous examples when we used an array here we actually just walked past the end of the array and continued looking at memory locations that weren't actually part of the array if we try to do the same thing here with the array container we actually crash with a debug assertion failed because our array subscript was out of range so our code crashes here rather than just running past the end of the array and continuing to process memory now it turns out that with the scores container we obviously can use the square bracket notation to access an element of the array but we can also actually use an at function to access the element of the array and if i do that we get a separate debug error but it actually still aborts it still stops us from going past the end of the array this at function is a safer way to access elements of the array this crashing when we use square brackets is not in the c plus plus standard in the c plus plus standard walking past the end of an erase container still works the same way as with arrays so that was a visual studio thing that this crashes when i walk past the end of the array container with square bracket notation but in the c plus plus standard using at will always crash no matter which compiler you're using as long as it implements the c plus standard so the safety of using at across any c plus plus compiler is really one of the big wins of using an array container rather than just using an array to recap in this lecture we explored using the array container as an alternative to using arrays and we also learned about the at function which keeps us from indexing outside the array bounds which is a great thing so we don't just start walking through memory that's not part of the array even though we think it is arrays are available in almost every modern programming language but almost always as in c plus plus we need to know exactly how many elements we need in the array when we create it the same is true for the array container in c plus plus the vector container doesn't have that limitation so what can we store in a vector anything but every element of the vector needs to be the same data type and the big win for us is vectors can grow and shrink as necessary as we run our code our starting code is the code from the previous lecture and this time we're going to convert from using the array container to using the vector container and the big win here is that our vector container can change in size at runtime so we're no longer constrained to having an array of a specific size or an array container of a specific size we can just have a vector container that grows and shrinks as needed that also lets us have the user provide at run time how many scores they want to enter and then we'll have them enter that number of scores so let's get started we'll change this array to vector we no longer have to provide a size because as i said the vector will grow and shrink as necessary however we have to come up here and instead of pound including array we need to pound include vector and now our scores variable will be a vector container of ins we have some work to do get how many scores so we'll prompt for and we'll tell the user what the valid ranges and i'll need a variable to store their answer in so i'll just store num scores so now i'm reading in how many scores they want to enter and of course in practice we need to do a while loop here to make sure that they entered a valid number that's not the point of this lecture so we'll blast past that part so now we're going to read in the scores and i know i'm going to want a line break before i do that but we can't do scores dot size at this point we could do scores dot size but scores dot size will tell us 0 right now because we haven't added anything to our vector yet so we're going to use num scores here just for this one as we populate the vector the other thing we're going to need to do is we're going to declare a variable to hold the current score that the user enters so we're not reading into scores i anymore we can access elements of our vector using the square bracket notation just as we see here but because we haven't filled up the vector yet we'd be trying to access elements that aren't actually in the vector yet so i'll change all these scores i in this for loop and while loop to that variable that we have right here and now at this point right before we go back to the top of the for loop again at this point score is a valid score but we haven't added it to our scores vector yet the way we do that is we say scores and we call the push back function which will put the score that we just got at the back of our vector so this is how we fill up the vector and add things to the vector that's our sort of first new thing for the vector in addition to being able to dynamically say how many scores there are going to be so now we calculate the average again the vector container is a range so it has an iterator so we can use the range-based for loop here and it has a size function so we can find out how many things are in the vector right now and then we can print out everything in the vector and the average just like we've been doing so if i run the code here so i'm going to say i'm going to enter three scores and now i enter the three scores and as you can see it calculates the average properly and iterates over the scores properly just as we'd expect one more thing i want to show you the vector container has lots of different functions we can call as you can see we've got pushback we've got size there's another function that you might find convenient to use periodically so i'll say clear the scores i can do this i can take my scores vector and i can call the clear function on that vector and now if i run the code i'll enter three scores again one two three and it calculates the average just fine but the vector is now empty so when i get to this for loop scores dot size is zero and zero is not less than zero so we don't even print out any scores so the clear function empties the vector and you'll find this to be really useful if you have a vector field in a class and you want to reuse that vector multiple times as your program runs i'm going to comment this out before i give it to you and we can see one more time that we're back to working the way we used to work to recap in this lecture we learned how to use a vector instead of an array or an array container when the number of elements we need to store is likely to change over the last few lectures we've explored the c plus array and vector containers in this lecture you'll learn about the unreal t array container which is the container you should use in your unreal games what can we store in a t array anything but a particular tra can only store a single data type and t arrays can grow and shrink as necessary as our code runs we're not going to look at any code in this lecture because we're going to use the unreal t array container in the next lecture however this can be a little confusing because first of all you should not try to use the standard containers in unreal we should just use the containers that are provided in unreal why did i teach you those c plus plus containers because i'm teaching you both c plus plus and unreal engine but despite what we learned about the array container and the vector container in the previous lectures when we're in unreal we'll use the t array container now the reason this can be a little confusing is because the t array container in unreal basically corresponds to the vector container in pure c plus so it's too bad this is not called t vector there is a t vector in unreal but t array is what we want to use for dynamically sized containers of things so the big idea is tier a is our container and i'm going to scroll down and talk about a few of the things in the documentation but really we'll put this into practice in the next lecture so it's a container it can dynamically grow we do have to store only one type in it so it's a homogeneous container it can only store a single data type for each of the elements just like we had for both array and vector containers in pure c plus plus so we create an array like we created a vector in standard c plus plus so we put t array it's a class template just like the containers we've looked at so we put the data type of the elements and then we put the variable name this gives us an empty array there's no memory allocated yet it's just like an empty vector and we can populate them in a variety of different ways you'll typically see me use add as the function to add elements to my t array variables there is an in place function as well but i'll typically use add we can also append so we can add a number of different things to our t array all at once so this is actually helpful we can insert an element at a particular location in our t array rather than just pushing it on the back of a vector for example we can iterate over our t array variables either using the range based for loop because the t array is a container that has an iterator it is a range and we can also use a standard for loop if we choose to do so and as you can see here we have a num function that corresponds to the size function for the c plus plus array and vector containers and that's a whirlwind tour of the tra container in unreal we'll learn about how to use all the capabilities we need as we need them as we use the tra container in our unreal games to recap in this lecture you learned about the unreal t-array container and you learned that that's the container you should use in your unreal games and we also learned that the unreal t array container is similar to but not identical to the c plus plus vector container in this lecture you'll see how a teddy bear can collect things using t arrays of course let's go take a look we'll start by talking about how the game actually works and then we'll look at how it's implemented so when i run the game i have ted the collector here and i can right click in the game world to place a pickup for ted to collect and i can place multiple pickups along the way as many as i want but when i left click ted will collect the pickups in the order in which they were placed so ted will always pick the oldest pickup first you can see ted just passes right over other pickups i can start him collecting and then add more and he'll keep going but once he's collected all the pickups in the game he stops and waits for another left click to start collecting again we have a number of c plus classes here we have a class for the pickup and i did that not because a pickup has behavior but because i wanted to create a blueprint from that pickup i have a pawn and a player controller for ted and i have a custom game mode that i've used to set up the pawn and the player controller in the ways you've seen me do that before in our content you can see i have the blueprint for the pickup the blueprint for the pawn and the blueprint for the player controller now there is some configuration stuff that i had to do for collisions to make sure that collisions worked properly in other words i didn't want a physical collision between ted and the pickups i wanted ted to be able to pass over them and sort of trigger when ted overlaps with one of those pickups so that i could either ignore that overlap or i could say oh this is the target pickup that i was trying to pick up to do that in the pickup the static mesh for the pickup i needed to set up a custom collision preset enable collisions and i marked this object as world static and i have it so it blocks physics bodies and ted is a physics body and very importantly i checked this box that says generate overlap events so when an event occurs i want the engine to tell me that that happened and we have to click that box to make that happen so the other thing i had to do is in the pawn in the static mesh for the pawn i also had to click that generate overlap events custom again i am a physics body and i said i want to overlap with world static objects so those are configuration things that i had to do to make it so that the engine would tell me when the ted pawn overlaps with a pickup let's go take a look at all the c plus plus code that i wrote to make this game work in the playercontroller header file i declared a property so that i could populate in the editor the pickup so that when i right click i will place a pickup so this is the actor that i'm going to place when i right click i'm setting up my input component as you've seen me do before with player controllers i have a place pickup function so that i place a pickup on particular input specifically a right click i collect pickups on a left click and i destroy a given pickup when the pawn tells me i've run into the target pickup the pawn will call this function so that i can destroy it and take it out of the t array so i wanted to do this particular game in this lecture so that we could use a t array to maintain our set of pickups that we've placed and because we will add our pickups to the end of the t array the ordering in the t array the front of the t array the element at index 0 is the oldest pickup so that will be the target i want to point out that i didn't mention this when we were talking about t-rays in the previous lecture but it's very important if you have a t array field that you mark it with the u property macro that's so that the engine does appropriate garbage collection it's not because like we did up here so we could edit it in the editor or anything like that it's to make sure that garbage collection works properly on this t array so if you're ever declaring a tra field you need to mark it as you property i also have this boolean that tells whether or not we're collecting and when the game starts we're not and i have one more function that tells ted to go to the next pickup and we'll see how that all works in a moment in the implementation file i've set up two action mappings i set up one for place pickup with the right mouse button and will respond when that is released and we'll place a pickup and i defined another one called collect pickups that responds to the left mouse button being released and we'll call the collect pickups function how do we place a pickup well we figure out where the mouse is because we want to place the pickup where the mouse is right now and remember we used this when we were doing mouse input to make our character follow the mouse this is how we figured out the world location of the mouse position setting x to zero so we stay in the yz plane and so i'm using spawn actor here just like our spawners have used to spawn a pickup specifically the one we populated in the editor at this world location not rotated now previously when we used spawn actor we sort of just had this but this function actually returns a pointer to the pickup that got spawned and we need that because we want to include it in our i said list of pickups here but it's really rt array right this is the t array and we've added this new pickup that we just spawned into the world and the add function adds this pointer to a pickup at the end of our t array and that's what keeps our t-ray in chronological order where the front is the oldest and the back is the newest when we left click so this function gets called if we're already collecting we just ignore it we say okay well i'm already collecting so i don't care that you left clicked but if i wasn't collecting on a left click i go to the next pickup and here's how i go to the next pickup if there's at least one pickup in our pickups t array so the num function tells us how many elements are in the t array right now i get the target pickup we know it's at index 0 and i put it into a local variable and remember this is a pointer to a pickup actor not the actual actor and then i remove this pickup from the t array and the remove at function lets us provide an index and it will remove the element that's at that index so first we have to grab it and save it and then we take it out of the t array because we don't want it in that set of pickups that we still need to go pick up once we've done that we get our pawn that we're controlling and as long as it's not a null pointer we tell our pawn to go to that target pickup and we'll take a look at that when we start looking at the pawn so here's where we called go to next pickup the other thing is when the pawn reaches a target pickup it calls this function to say destroy it and we need it to happen that way because the player controller is maintaining our t array of pickups so it has to know when the pawn has reached the target pickup so the pickup gets passed in and we remove it from our t-ray and we destroy it out of the game world and now we know there may be more pickups that have been placed in the world so we want to go to the next one and we already looked at that go to next pickup function that's it for the player controller for the pawn we need a reference to the static mesh component for the pawn because we're going to push the pawn toward a pickup and to use the physics engine to add an impulse we need the static mesh so i'm saving it here in a field so that we don't have to go get it every time the pawn is sent to another pickup so that's an efficiency thing we have the typical constructor and begin play and tick here's the go to pickup that the player controller calls in the pawn when it's supposed to go to a pickup and it passes the target pickup into the pawn this function right here is going to act as what's called a delegate for when we get an overlap between a pickup and the pawn unfortunately there's lots of stuff we need to know sort of all at once before we can do interesting things but just trust me and i'll talk through a little bit about how this works but i promise you we'll actually be talking about delegates in much more detail in the last course in the specialization i have a constant for the magnitude of the force i'm going to apply to the pawn when i get it moving i have a target pickup that i'm going to save and we'll see why but i've saved it as a field so that it persists in the pawn as time passes because we'll need that to detect when we get an overlap whether we're overlapping with the target pickup or not and then finally a utility function to get the force vector between two locations because when we need to go to a pickup we need to figure out the direction and the magnitude of the force to apply to the pawns static mesh to do that and this function helps us with that job in the implementation file for the ted pawn in begin play this is where i'm saving the static mesh component so here's a two array just because we need a t array as our argument here forget components so basically what we're saying is we're going to have a t array of pointers to all the static mesh components that are attached to the pawn and then we call the get components function with static mesh components to populate static mesh components so when we get to line 30 static mesh components is a t array that has zero or more static mesh component pointers in it we check to make sure there's at least one and if there is we take it and we save it into our field and remember we're doing all of this work because the static mesh component is the thing that will add a force to to actually get our pawn moving this is the delegate thing so our static mesh component we're saying when the on component begin overlap event occurs so we've just entered an overlap on this frame with the static mesh component for the pawn and something else we say call this on overlap begin function that we wrote we've seen this sort of thing before right when we bound functions to be called when input is provided this is the same idea it's just a little more complicated and like i said we'll discuss this in much more detail in a couple more courses here's that on overlap begin so here's what i do the parameter that i care about if this function gets called is the other actor the thing that the pawn is overlapping with so first of all i just make sure there's no error in the way this function has been called and then i check to see if the other actor is the target pickup if it isn't i'm all done i don't have to do anything i just keep moving along my velocity vector the way i was before this is not the pickup you're looking for but if it is the target pickup i want to stop the pawn so i do that by calling the set all physics linear velocity function to zero so as you can imagine right i'm setting linear velocity to zero so that means stopped and i also do that on the static mesh component so we're applying these physics things to the static mesh component the other thing i do is i get the thing that's controlling me right now we haven't seen this before but it's similar to the get pawn from the controller side this is from the pawn saying who is possessing me right now making sure that we get the ted player controller and if we do we call the destroy pickup function with the target pickup the one we were looking for and then as we saw the ted player controller removes that pickup from our t array and destroys it in the world and then moves on to the next pickup the go to pickup function we save the pickup that gets passed in as a parameter into our target pickup field and then we get the force vector from the pawn get actor location and the location of our target pickup and that gives us the force vector and then we add an impulse this is an impulse force so think of it as whacking the pawn with a baseball bat or something and it will whack the pawn with the baseball bat it will add an impulse force in the direction of the force vector with the magnitude of the force vector finally that last function i was talking about the get force vector we simply subtract ted location from pickup location so that gives us a direction but the direction has a magnitude that is based on how far away the pickup is from the pawn right the pythagorean theorem tells us that the magnitude of this direction vector will be dependent on the distance so what we do is we normalize the direction vector so it is a pure direction vector so when we normalize a vector we give it a length of one so no matter what direction it's pointing in its length is one but it's pointing from the pawn to the pickup and then finally we return that unit vector multiplied by force magnitude and that's the force vector that we want to apply so i know that's a lot of coding a lot of new stuff but this is a really good way to implement the game as i showed you before i finish i'm going to show you a flaw in the game i probably shouldn't but i will so back in the editor if i run the game and i place two pickups really close to each other watch what happens when the teddy bear goes he just leaves and never picks up the next pickup so the issue is that the on begin overlap event happens on the beginning of an overlap but when we ended up hitting that first pickup we were already overlapping with the second pickup so the event was never fired so we couldn't pick it up there's certainly a way to solve this problem we can take a particular actor like the pawn and we can find out all the actors we're currently overlapping with so when we're told to go to a next pickup we could actually check to see if we're already overlapping with the target pickup and if we are we could immediately tell the player controller okay destroy the next one i'm already there that was more complexity than i wanted to add because i think we have enough complexity as it is in this game but that's also a solvable problem to recap in this lecture you saw how we can use t arrays in a small game congratulations on making it through the second course in the c plus programming for unreal game development specialization i hope you enjoyed the course and i hope you learned a lot as well and if you feel like you have enough to just go off and start building your games then go ahead and do that if you'd like to learn more about both c plus and the unreal game engine then you should just move on to the next course in the specialization no matter what i appreciate you're joining me in this course i really have a blast doing these courses and i'm glad you came along for the ride cheers