Transcript for:
Beginner AI Behaviors in Unity

welcome back to blackthorne prods today we'll learn how to create five simple but extremely useful air behaviors you can use in your game projects this is a beginner-friendly c-sharp and unity tutorial we'll see how to make enemies follow a prayer character make a line of sight simple 2d pathfinding so characters actually avoid obstacles a patrol behavior and even a sneaky shoot and retreat creature remember that we also have five quality game death courses on username each teaches you how to make art sound and code for different game projects from a platformer adventure to a fun online multiplayer arcade experience so if you like our teaching style consider giving those mega courses a look links are in description alright so let's start off by creating our first enemy ai which is this basic follow enemy so he'll just follow the target around and stop once he reaches a certain distance to him so i've got an empty c-sharp script attached to enemy character let's now open it up and i'll show you how to close this simple behavior let's start by creating our variables so we're going to need a public flow variable for the speed of our anime as well as a public transform variable for the targets that we want him to follow lastly we'll make a public float variable called minimum distance that will be used to stop our enemy once he gets close enough to our targets now to make him follow the player there is nothing more simple we just need to go inside of the update function and set our transform dot position to be equal to vector 2. move towards this function takes in three parameters the first one is the starting position so we will put in our current position so transform dot position the second is the target position we want to go towards so i'll pass in our target dot position and lastly the third is the speed at which we want to move so i'll use my speed variable and will not forget to multiply it with time delta time to make the movement frame rate independent now to make him stop moving once he gets close enough to the enemy will wrap our line of code inside of an if statement this if statement will check if vector2.distance between our current position so transform.position and our target position is greater than our minimum distance variable so if he is not yet close enough then he'll continue to move towards the targets now if you wanted your enemy to start attacking once he's close enough then you should probably want to create an else statement here and write your attack code in here now back instead of unity we just need to fill in this variable and drag and drop our targets and we are good to go in just a couple of minutes we've got this very simple but highly effective enemy ai that you could use in so many different games okay let's now move on to our second enemy type which is this enemy that shoots projectiles towards our player and he also retreats when the player gets too close to him so for the script we're actually going to start with the same script that we created for our basic follow anime to create the defensive retreat behavior we just need to make two small tweaks to this code instead of using our speed variable we'll just use the complete opposites so negative speed this will make him retreat and we only want him to retreat so when our distance is smaller than our minimum distance if now press play you will see that with just those two small tweaks our enemy is now retreating instead of attacking now let's get some shooting some projectiles towards our player so let's start off by creating a bunch of variables so first of all we need a public game object variable called projectile that will store our projectile prefab then let's have a public float variable for the time between shots as well as a private float variable called next shot time that will store the time at which we can shoot another projectile now instead of the update function i'll create enough statements checking if the current time in the game so time.time is greater than or equal to our next shot time variable if that's the case then we want to shoot a projectile so i'll instantiate our projectile prefab after a shot point dot position and with no particular rotation so quaternion dot identity of course we also need to set our next shot time to be equal to the current time in the game plus our time between shots variable okay and that's all we need inside of the script let's now come over to our projectile prefab and let's open up the projectile scripts this script will be in charge of actually moving the projectile towards the player so let's start off by creating a vector3 variable called target position we'll also need a public float variable for our projectile speeds now inside the start function i'll set my target position variable to be equal to find object of type prayer controller so that will find the object in our scene that has the prayer control script attached to him and then we'll say dot transform dot position to retrieve our player's exact position now inside the update function we'll set our transform.position to be equal to our famous vector 2 dot move towards function the starting position will be our current transformed up position the target position will be our target position variable and we'll use our speed multiplied with time delta time okay then i'll quickly check if transform.position is equal equal to our target position so if our projectile has reached our target position then we will simply destroy this game objects alright we are done so let's save a script and head over back to unity so let's select your enemy fill in these variables and drag and drop our projectile prefab inside of its respective slots then we'll go ahead and select our projectile and we'll also fill in our speed variable here and with that our retreating shooting enemy is now complete i really encourage you to be creative and to mix and match different anime ais to create your own unique one for example you can mix this enemy ai with the previous one so the enemy sometimes retreats and shoots and sometimes goes on the offensive and starts charging towards the player okay so our third enemy ai is this cool patrolling enemy so he basically has a bunch of patrol points that he moves towards one by one this enemy ai is so versatile and we use it in so many of our different game projects okay so let's open up the new enemy script and start coding this functionality so for variables we're going to need of course a public float variable for our speeds we will also have a public array of transforms for our patrol points we'll also create a public float variable called wait time which we'll use to control how long the enemy stays on each patrol point for lastly we'll also need a private integer variable called current point index that will store at which patrol points our enemy is currently moving towards now inside of the update function we'll set our transform dot position to be equal to vector 2. move towards we'll go from our current transformer position to our patrol points with an index of carrot point index dot position and for the speed we'll just use our speed variable multiplied with time dot delta time now we'll wrap this line of chords in an if statement checking if our transformer position is not equal to our patrol points with an index of carrying point index dot position so if we have not yet reached our patrol points then we will continue to move towards it elsa so if we have reached our patrol points then we want to wait and then start moving to the next one to do so i'm going to start a curtin the alcohol weight now let's create our i enumerator called weights in here we'll start off by saying yield return you wait for seconds we'll pass in our wait time variable now that we have waited for the correct amount of time we also start moving towards a new patrol points to do so we just need to increase our current point index variable by one now of course we only want to do that if current point index plus one is still smaller than our patrol point array dot length if it's not that means that we are at our last patrol points and so we will just want to set our current point index variable back to zero so that he goes towards our very first patrol points and so our patrolling behavior will continually loop now everything should work except for one problem and that's that's this weight coroutine is going to get called multiple times whereas we want it to only get called once when we reach a new patrol point to fix this i'm going to use a very simple technique so i'm just going to create a bull variable called once then we'll just wrap our start curtain line with an if statement checking if once is equal equal to false then inside of the if statements just above our start coroutine we'll just set once to be equal to true this way it will make sure that our curtain only gets called one single time of course at the end of our curtain we'll set once back to false so we'll be able to call the curtain once our enemy reaches his next patrol points and that's it so let's save the script and head over back to unity now in here we just need to fill in these variables and of course drag and drop our different patrol points inside of this array the patrol points are just a bunch of empty game objects that we created and we scattered around the scene okay our patrol enemy is now complete like i said before you can use this enemy behavior in so many different ways so be creative and have fun with them all right so our fourth enemy ai is a really important ax to have in your arsenal and that's an enemy that can actually move towards targets but at the same time avoid and go around different obstacles that there might be to make this behavior we're going to be using a special algorithm called a star pathfinding but instead of coding that algorithm ourselves which would take quite a lot of time and is quite advanced we're going to use an awesome pre-made a-star package that we can download off the internet for free you will see that in just a couple of minutes everything will be up and running so head over to this link and we'll also put the link in description then just click on this download button under the free version section once it's been downloaded it will prompt you to import a unity package inside of your projects so just go ahead and import the entire package so in my scene i've got my poor character like usual with this enemy character and we also placed a couple of rocks in the scene that will act as our obstacles we're going to start off by creating a empty gum jinx the alcohol a-star this object will be in charge of letting your enemy know which part of the game world he can move on and which part he can't let's go ahead and add a new component and let's search for pathfinder what has been added let's come to the graph section and let's create a new grid graph so this grid graph is basically going to create an invisible grid on my entire scene then each grid cell is going to check if it's on an obstacle or not to see if our enemy can navigate on that area so because we are in a 2d project i'm going to select 2d once we do that so you'll be able to see what the grid looks like now let's go ahead and take our skill tool and then just resize it so the grid fits nicely on our player area let's also check the use 2d physics option we also need to define a layer for all the objects that we don't want to animate to work on so i'll select my obstacle layer that is the layer that all my rock obstacles have got they also have a circle collider 2d on them now we can click on this scan button you will see that our grid has detected where obstacles are and has marked those grid cells red you can control the accuracy of the cutout with this diameter variable so the smaller the value is the tighter to the obstacles your enemy will be able to walk on and the larger the value is the more space you'll have to give around the obstacle okay we are finished with our graph so let's just click on this eye icon to hide the graph now let's select your enemy and let's add to him the ai path script this will also add the secret script with it we will then select y axis forward for the orientation which is the correct one for a 2d game you'll now see this yellow circle around our enemy this represents his physical boundaries basically it will let our pathfinding algorithm know how big our enemy is you can control the radius of this circle here to make it fit nicely we also don't want any gravity in our game so we'll just select none let's also disable any rotations on our objects now we need to add a last component which is the destination settler components so we can drag and drop a target for enemy to chase so i'll of course drag and drop my player character and if you press play you'll see that your enemy is chasing the player perfectly avoiding any obstacles on this way this is really cool you can of course control the speed of your enemy with this max speed variable okay let's now tackle our fifth and last enemy ai which is an enemy with a line of sight so basically this enemy is going to be rotating and he has this line of sight detector the line turns red when it hits an obstacle and green when it doesn't so yeah i'm going to show you how to create this simple line of sight behavior but then you could go ahead and complete the ai in any way you want for example you might want your enemy to start moving towards the player once he spots him or you might just want to restart the level if the enemy detects the player if you're creating a sort of stealth game alright so let's open up our brand new enemy script the first thing we want to do is to simply rotate our anime over time i'm going to create a public float variable called rotation speeds then inside of the update function i'll use transform.rotates inside the parentheses i'll say vector3d forwards which will make him rotate on the z-axis which is exactly what we want multiplied by our rotation speed variable and of course multiplied by time or delta time to make the rotation frame rate independence all right back inside of unc i will assign a value for my rotation speeds and now if you press on the play button you'll see that he is nicely rotating over time okay now let's create the line of sight functionality to do so we're going to be using raycasts so to create a 2d array we're going to use the physics2d.raycast function the first parameter that we need to pass in is the origin of the ray so basically where it starts so i'll just use my enemy's current transform dot position next off we need to pass in a direction in which the ray should point towards so i'll just say transform.right finally we need to specify the length of the array so i'll come up to the top of my script and i'll create a public flow variable called vision distance and then i'll use that variable has my third parameter when working with raycasts it's always a good idea to visualize them to make sure everything is working like plants so that's exactly what we're going to do now all right so we're going to store this raycast information in a raycast hit 2d variable called hit info now that we have that we can check with an if statement if hit info.collider is not equal to null so basically we're checking if array collided with any objects if it did then we'll say debug.drawline with the origin being our transformer position the endpoint being hit info dot points which refers to the point of contact of the ray and finally for the color we'll use color.reds elsa so if array hasn't hit any obstacle then we'll also do a debug.drawline but this one is going to be a bit different the origin will stay the same so transform.position but for the endpoints we'll say transform.position plus transform.write multiplied by our vision distance variable this will make our line go in the same direction as our raycast and have the same length as it as well this time we'll give it a green color of course inside of this if state expense you could check if hit info dot collider tank equals equals player for example so this would be where you would want to check if your raycast hit the player if you wanted to take this ai further and do different stuff with him once he spots the player but for the sake of this tutorial i won't do anything special in here alright let's see the script and head over back to nancy i'll now just assign a value from a vision distance variable don't forget to also have colliders attached to your different obstacles as well as the player otherwise it will not work pressing play you'll see in the scene view that are raycasts are working perfectly now these debug draw lines are only visible in our scene view and it won't appear in our finished game if you want to actually show the player the line of sight of the enemy we're going to have to use a line renderer to do that so i'll create a brand new game object that i'll call line of sights once it's been created i'll add to it the line renderer component now to be able to visualize it i'll just move the two points little apart you'll see that at the moment the line has this ugly magenta color to fix this i'll come down to the material section and i'll select the sprite default material you can now change the width of your line right here alright let's now jump back inside of our scripts i'll start off by creating a public line renderer variable called line of sights now a top over update function will set our line of sight's first starting point to the point of index 0 to be placed at your enemy's transform.position then if we hit a collider with a raycast then we want our line of sight second point so the point of index one to replace as the point of impact of array so hit in full dot position we'll also change the color offer line by setting the start color as well as the end color of the line to color.reds now if a raycast doesn't hit any collider then we'll set our line second point of index 1 to be placed at transform.position plus transform.write multiplied by our vision distance variable and this time we will set our line start and end colors to be equal to color.green okay we're all done so let's save the script and head over back to unity i'll not forget to drag and drop our line of sight inside of the slots and we can now test it out and that wraps up the fifth and last enemy ai of the video we have now got this cool line of sight anime that you can expand in so many different ways hopefully you've found this tutorial helpful remember to like and subscribe it means a lot and also check out our game dev courses on youtube whereas videos like this teach a random topic the courses bring you through the entire gamedev process by making a video game from a to z from coming up with an idea and creating rough sketches to designing and polishing you'll get a huge discount if you use the links in the description stay tuned for more game news tutorials cheers you