Creating a Basic Turret AI for Unity 3D - C# Beginner guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this tutorial i'm going to show you how you can make an enemy ai turret this one will fire upon you once you're in a certain range of proximity so stick around for that [Music] all right you've lasted through the intro now i want to make sure that you can keep track of the tutorial properly so i like to start off with a brand new project i'm going to go ahead and create this project and we'll hop right into unity it's loading right now on my other monitor i bring it over it is and while this load check out the quick announcements and i'll be right back into the tutorial quick announcement guys this will take about 10 seconds of this video and then right back to the tutorial got a new youtube channel it's called leaking show where we talk about hard times and just basically trying to make the world smile again everybody be happy i know a lot has been happening just a lot of bad news all across the internet and so this channel is dedicated to just addressing some of the some of the not so talked about topics and very basically bringing light to it uh doing some interviews with people that's going through tough times just hearing their opinion on how they get through it all just to help motivate other people that's going through those similar kind of things and basically just just memes and and making people smile again so check it out show your support by subscribing to that channel as well uh next announcement just real quick is a book released on amazon as digital book just go ahead if you have the kindle unlimited it's completely free it is 0.000 so hey why not and definitely leave a review uh next now so you guys already know that i am a teacher and i teach kids to code so if you guys are ever interested in learning to code whether you're a kid or an adult check out the online code coaching and just go ahead and send me a email to info at online coaching doc and the final announcement is mod storm what is milestone you ask you didn't ask well basically you don't have to download anything you don't have to code anything but you'll be making video games straight from the web cross platform just like roblox except better so it's going to be a very very big deal you don't want to miss out i'm making some videos showing you how to use it coming soon so subscribe for those back to your tutorial thank you for waiting all right so now that unity is loaded up i'm going to use one of the unity third-person controllers to kind of speed things up with this so i'll go ahead and check out my assets and i'll go ahead search for a third you can find this one here on the asset store it's just a starter asset by unity with a third person controller i'm going to import this into my game so i have a character that i can run around with and then we'll go right into building our turret from scratch [Music] all right so once the unity assets as imported you'll see that there is this little pop-up that's talking about the new input system and how it needs to be disabled enabled old one blah blah blah so uh you're gonna hit yes on this but it will disable the old unity uh input scene and it may restart your unity project see it's quitting unity now and it's going to restart my project my project is loading up again keep in mind that this does disable the old input system so if you're doing this in an existing project you might find that some of your buttons and your inputs that are tied to the old system will stop working but i got you don't worry once your project loads back up just go ahead and i'm gonna show you how you can make sure that both the inputs are working from the old and the new so we go to edit and go down to project settings go to player right here and in these drop down menus you want to go to the very last one that says other settings right here active input handling it's set right now to the new you can set it back to the old or the best solution would then just be to set it to both at that point you hit apply it may restart your unity system one more time and it did all right so that will fix your problem if you were using an existing project i do recommend though start getting into using the new input system as it is very easy for cross platform so check out videos on using the new ecosystem so from what i've downloaded there is a sample scene in here somewhere let's see if i can find it right and in here i already have a third person controller that's set up to work i can look around walk around hold shift to run and jump around as well so this is amazing all i need now is to set up my turret so we can get on with this tutorial let me go do some cosmetic work on this scene because there's a little bit too much happening i'm gonna delete a few structures and then we'll go ahead and build our turret from scratch [Applause] so there you have it i've made my makeshift dirt just a cylinder cube on top and a other uh canon barrel part just showcasing where the bullet will come from um keep in mind that the forward facing of the turret is the uh the blue arrow so when i click on the cube that i place on top the blue arrow is pointing that way so it makes sure that the cylinder part that is the barrel comes out from that direction because um the head which is the top part here that will be the part that rotates around for aiming purposes so you want to make sure that when you tell it to look at the player this is the front that's going to turn all the way around and point at the player so you want to make sure that the head the barrel is coming out from that side hopefully that didn't take too long because now we're about to actually get into the meat of what we're trying to do we have a working character that can run around now we have our little makeshift turret all we need now is some code on this bad boy and boom we're in it so let's go ahead and start by creating our new code and add this to the turret i'm just going to drop everything in here in the assets there's really just a tutorial so there's no need for me to be all organized but i do recommend that you put your script in your script folder so i'm going to call mine uh turret control and i'm going to put this on my turret once unity is done processing the script jumping on the turret and it's time to crack it open why do i say crack it open like it's an egg or something it's not it's not an egg so script is here and we're going to do some coding all right so script will be really simple here a couple of references we're going to need um we'll need a reference to the player you don't want to make this public just in case later on uh you're going to mass produce these ai enemies or maybe even spawn them in so you just want to go ahead and make it private so we need a transform reference to the player so the enemy knows who to target and i didn't go ahead and make it public because like i said you might want to spawn these in later so when they spawn into the game the start function will will fire off or if you just mass produce them again the start function is where you're going to tell it what player is so we're going to tell it here that player i just call it underscore player because i like that better so i've renamed the variable the reference to underscore player and i'm gonna say underscore player is equal to a game object that is in the scene and if we can just find that game object we could just find that game object with a certain tag right so don't click the find game objects because that's the plural but find a game object singular and i'll just provide it with the tag player like so once you find that game object go ahead and give us the transform and store that transform information in underscore player so now this will automatically target that player and is transformed one thing to note is that the player himself you will need to come in here into your scene and find your player this is the one that came with my demo assets here and i just want to make sure that it has a tag player the tag is spelled play with a capital p i knew that ahead of time and that's why i also made sure that my tag here is player with that capital b now we're just gonna go ahead and create some variables that will help us with detecting the distance of where the player is so we'll create a float again doesn't have to be private or public we just go ahead and call it this for distance keep in mind if you don't like public it is private by default so when i said it doesn't have to be private or public i just mean you don't have to write private or you don't have to write public here but it is private by default right so i have distance or a variable called distance which is a number so in the update that happens all the time you already know how the update works i assume you're just going to tell it what distance is going to be changing to um on the fly continuously throughout the game so distance is going to be a distance so we're going ahead and tap into the vector three that has this functionality that gives us the distance of two um two positions that we will have to give it okay so you see the intellisense gave us a little pop-up there telling us it needs a a and a b a vector three so it needs an a and a b location our position so first one is going to be the player so that's the transform and we go into the position second one is going to be the turret's location so we simply say transform dot position anytime you mention transform it automatically is referring to the transform of the object that the script this script is on now we do know that this script is on the little makeshift turret that we made over there okay so now that information is will will be constantly refreshing and placed into distance so we have the distance in here between these two objects now all we need is some sort of logic to say hey if that distance is less than a certain number that means that we are close enough let's go ahead and make that number we'll make this one public so we can adjust it inside unity so public float and we're going to call it uh how close or you can say max distance or something like that that makes sense to you so now for that logic back into the update if that distance that we're getting continuously is less than or equal to our like max distance so my little how close then we will tell the turret so the head of the turret in particular to turn around and look at the layer let's make a transform reference to the head so we gave public it's a transform and we'll just call it head okay we're gonna tell that head to look at the underscore player and we're ready for a test i'll save it back into unity don't forget once you head back into unity don't hit play immediately you do have to do the configurations that you just made so back onto the turret over here i have the script i have the how close i'll say how close i'll say 20 and then the head which is the head part here of the turret that i want to rotate to look at the player i'm going to make that reference and link it to this right here the reference is head and it's linked so now when my code says head look at player then that means the head here is going to rotate and look at player anytime i'm within that 20 for my distance okay there we go oops let me just change that there you go um the rotation there we go okay so let's hit play for a quick test and you can see it's not looking at me or anything i'ma go a little bit closer to it here yep and there it is now it's staring at me as i walk around so maybe a little bit closer if i want to do closer now when i'm far away it doesn't care about me i'm not close enough as soon as i get closer cares about me okay and that's controlled using this number here how close so feel free to work around work with that and see how you really like it the next step here is you wanted to shoot let's go ahead and make a shooting functionality we'll go ahead and start off by making a new function and we'll call it shoot in here we'll simply have it instantiate a object and propel that object forward so let's create a public reference to what that object is going to be it's going to be a game object and we'll it'll be our projectile so underscore i'm just calling it project tile like so okay so we're gonna spawn that in when we shoot so i'll just say instantiate what we're gonna instantiate what we're gonna clone the original object that and where we're going to spawn it um we'll say we don't want to say transform we don't want to say the turret's position because third position will just place it at uh let's see let me show you what i mean we'll just place it like right here at the very center of the origin so where this box is if we say spawn at the head it will spawn it right here as well i kind of want to spawn it at the barrel location about like right here like right there so it like maybe in the center there so i did a reference now to the barrel um position so let's go ahead and make that before i continue you since it's going to be a transform i don't have to make another line so they have this line here what i'll just do is put a little comma and then i'll just say barrel like that all right so it's two variables that are the same so now say i want to spawn this at the barrel dot position right balance position and then as for rotation i will simply say transform the rotation i kept in mind that the barrel has a very odd rotation notice that the forward arrow which is blue is pointing down so i don't want my projectile to also say as forward as now i want it to say its forward is the same direction as this object is pointing the original object you have to put the script on it all right hopefully that's not too complicated but you remember transform right here and right here simply refers to the transform that the script is on so use that rotation but again then use the barrels position spawns that in there afterwards we want to simply just add some force forward um yeah forward so in order to do that we need to capture the clone that we have just spawned into a variable so we can tap into it and add force forward let's go ahead and put all of this into a game object that we can just call something like clone so game object clone equals that column we just spawn and now to push it forward we say clone dot get component and let's assume that we have a rigid body on it in order to add force for it so we say rigid body and then you will add force like so and then it needs which direction you're adding force will tell it to add force again in the transform forward so in the forward facing direction of the turret times a certain um force like a certain number for your force i'm gonna go ahead and give it a pretty high number here feel free to create a variable for this that's one thing i'm not going to show you i'd like for you to try maybe make another float variable somewhere up here that represents your projectile speed and replace my hard-coded five uh 1 500 with that variable but that is it for the shooting functionality now you just gotta tell it to shoot when it's looking at the player the refresh rate up here will make it shoot a lot like a bit too fast so if you simply put this there you could run into some problems so we do need some sort of shooting fire rate but for testing purposes let's go ahead and check out how ridiculous this will be so we're going to save our code and head back into unity to set this up all right so back into the script we have two new empty variables here that we need to connect the projectile and the barrel we understand that the barrel is going to be this so i'll connect it another thing is when it spawns in the barrel the collider on the barrel could cause some problems so we're just going to turn it off or remove it it's going to spawn right in there what i'm going to do is i'm going to create a sphere that's a child object of the barrel a little ball here and this is where the projectile would normally spawn so we see an example and then it will just kind of fly forward so i'm going to actually use this sphere i'm going to detach it from the child object so dragging it out and i will call it projectile and i will add a rigid body to it follow me here closely and i will turn off the use gravity then take it drag it into the folder now it's a prefab i can delete it from the scene don't go ahead of me here you need to take it now the turret and link it to this empty reference so take it from the prefab that you made inside of the folders not inside the scene it is removed from the scene take it and connect it here so it's going to spawn these in and shoot them for it let's see how it works it's going to be ridiculous based on the refresh rate we're going to fix that right afterwards so let's go ahead and get shot at by a ridiculous amount here look at me and look at that as soon as we get closer we walk away and it stops when we get close look at us and go nuts well what can i say that was fun well let's clean it up by using a fire rate system uh keep in mind you can use these scripts i've shown you for different purposes you don't have to use them for exactly what we're doing right now but the fire rate will help us make it so that it shoots at a slower pace one by one we also need a way to clean them up because when they fly off into space they will be traveling forever and as long as they exist your game will become larger and larger and larger the four the further away they travel so you do need some safe um clean up kind of script um some some a little bit of a cleanup script that will help you get rid of the lingering um debris or in this case projectile so keep those in mind for other things that you're creating unity all right you got to be a good coder let's go back into unity and make that script okay so now we have the shoot script let's go ahead and create the fire rate i'll head right up here and create um a few variables that will help us with the fire rate i'm going to create two floats so i'll say float uh public and float only one of them needs to be public but i'm gonna be lazy and just put them both public um we need our fire rate and we need basically our next next fire like when we shoot again next fire then as i'm calling this function i'm still going to check to see that it is ready to fire before i call the function so i'm simply just going to put an if condition here that says if and i'll say time dot time is more than or equal to oops more than or equal to our next fire right if that is the case then we'll go ahead and shoot but we're going to do something else before we shoot so we're going to go ahead just move the chute into this condition if time that time is more equal to fire right or fire or neck next fire so what is next fire going to equal to we'll say next fire is equal to time dot time one f divided by our um fire rate just like that then it shoots with that just go ahead and save also let's clean this up so like i said before uh we don't want the clone to um travel just forever into our zone so we're gonna head and just put a little delete command here that says delete clone but then with an optional comma here we're just going to add a time of death so we're going to say about about 10 seconds later and that will do it for us let's save and head back into unity and that should do it so in the turn control we have two numbers here you don't mess with the next fire that will fix itself so that's why i said that only one of these needs to be public um and as for the fire rate here um let's try something like 15 and see how it looks you see it's much slower you can watch this number here as it climbs up now if i turn this 15 um down maybe two you can see it fires slower all right let's say i put 1.5 now it's not going the right direction we we can see that there are still some issues here it's not going the right direction okay so my fault my fault my fault i know what i'm doing wrong so sorry about that we made mistakes hopefully you caught this before i did but the transform that we spawned at is on the main object if you remember the main object actually the feet not the head the foot is not rotated at all so it's the head that should be the um the rotation so we already made a reference to the head we just got to change it now and put respond in this at the rotation of the head and then using the head forward and that that should fix it let's recap the code real quick a couple of variables up top um using the start function to reference to the player check if we're within the distance then go ahead and make it look at the player using the fire right here to shoot and then cleaning up the clones after about 10 seconds you can change those numbers if you want you can also go ahead and make some sort of on trigger enter something to happen when the bullet hits the player but this is where we're going to end this you see now it shoots right at me [Music] you can definitely increase the impact um the fire amount here i can you can turn that up to go really fast you can also lower uh you can also turn up or lower the fire rate from within the editor so right here i have 15 you can go ahead 1.5 something like that so it doesn't shoot as fast as i have it so from here it's really up to you what you do you can see there it shoots only when i'm at a certain um distance so if i go too far away it doesn't shoot anymore and these balls here will clean themselves up after 10 seconds thank you so much for your time hopefully it wasn't too drawn out but this channel is dedicated to people who do know a little bit uni unity and those who don't so i tend to explain things a little bit too much sometimes it's a habit of being a teacher anyways thank you so much for your time and you have a wonderful day i'll catch you in the next one
Info
Channel: Online Code Coaching
Views: 9,510
Rating: undefined out of 5
Keywords: AI, OCC, Turret, Unity3d, who to, Bassic Turret, Beginner, unity game dev, game dev, unity tutorial
Id: XLCMrguxIs0
Channel Id: undefined
Length: 27min 49sec (1669 seconds)
Published: Tue Mar 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.