How to Create an ANIMAL AI SYSTEM in Unity - Ep1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody and welcome back to the channel today we're going to be covering an animal AI system this is the first episode so we're just going to be covering the very Basics as you can see we've got animals wandering around across our terrain then they'll take a little break and then choose a new random spot to move to and go again in future episodes we'll be covering stuff like predators and prey um feeding and eating different foods and interacting with the player in certain ways maybe you can kill an animal to get some food or some resources here we are a brand new scene and the first thing we're going to do is set up the terrain and import the required Library so if you go to your window and click on package manager should be packages and you're under Unity registry you're going to want to come up into this corner and just type in Ai and you'll see AI navigation going to go ahead and install this the reason for this is it has the navigation components that we need to use for our AI it'll allow us to select certain points and move our animals to those points stuff like that just makes it really simple so after installing that you're then going to want to go ahead and create a brand new terrain so I'm going to go through the object terrain and to this terrain I'm adding a nav mesh surface so add that component there and you'll see we have a bunch of variables and stuff like that you can ignore most of these won't really matter at depends on what you're doing so I'm going to go ahead and just make my terrain look a little bit more interesting and then I'll come back around so we are back in my scene as you can see I just edited the terrain slightly made it a little bit more interesting and added a quick texture um coming back to your nav mes surface there's one thing you need to do and it might take a minute or two but you need to come down here and click bake and this will just bake our area so that we can um like navigate our animals across this surface so after baking it you should see this little AI navigation thing pop up and you can click show nav mesh to see what our walkable area is there are certain things you can set up to make it so steeper slopes are inaccessible to animals if you add certain objects stuff like that that you don't want the animals to be able to walk through you can go ahead and add a nav mesh obstacle to those objects so let's say we have a cube here we don't want anyone to be able to walk through it we just add this nav mesh obstacle and this will act like a box collider for the nav mesh um agents which is what our animals will be using so you would want to add that to anything like trees and rocks so on but for me I've not got any that so this is perfect just ready to go so one last thing I'm going to do is I'm going to come down to our surface here and just set up a little Cube that I'm going to be using for my animals this is just going to be a sheep so I'm going to call it a sheep I'm going to remove the Box glider you can keep it on there but I don't have no need for it and we're adding a nav mesh agent reset my rotation on this Cube so I'm going to go ahead and actually create a brand new model for this um anim that we're setting up here because I want it to be a sheep so the first thing I'm going to do is just click off a mesh renderer I'm actually just going to remove the mesh renderer and the cube filter right click and I'm going to create an empty object clip model I'm then going to right click inside of my model and create another white Cube shrink it down a little bit just like so and then create a little face by duplicating it just like this and I'm going to apply this a black material and close enough looks like sheep that'll do just fine so back on our navish agent here what you're going to want to do is come to this stopping distance and I like to set this up a little bit to something like three and then we're going to go ahead and add a new script by cing add component new script and we're just going to call this script animal so now I'm going to open up my animal script and we're going to get started so here we are in our animal script and the very first thing I want to do is import a new library so we're going to type type in using Unity engine. a and this is going to import our nav components and other stuff like that and allow us to actually use those in our script we're then going to want to create a public enam and we're going to call this animal State because we're going to be using State machines to control the behavior of our animal so I'm just going to type in idle and moving because these are the only two that we're setting up um in today's episode and one last thing we're going to want to do above our class is actually require components type 12 and then inside here we're just tying navish agent and this is just to ensure that we always have an nav agent um attached to any animals that we are trying to create just to avoid some uh potential issues so I'm going to go ahead and actually delete these two void start and void update and I'm going to just set up some variables so this first one is going to be controlling our Wonder state so you're going to want to create a public float we're going to call this first one one distance and this will be about 50 m this is going to be how far the animal can actually move in one go then you're going to want to create a public quat walk speed and I'm going to set this to be about five this is how fast your animal will actually move around and finally we're just going to create a Max walk time oh sorry a public vot Max walk time and this is going to be equal to maybe 6 seconds this is just how far your animal can move before taking a break and going into it going back to its idle State beneath this we're then going to create a new header and we're going to call this our Idol and this is going to have a public float Idol time in it and idle time will be how long the animal actually takes a pause or break for before it then continues to wander again need this we're then going to create a protected nav mesh agent and the reason we're doing a protected nav mesh agent is because in the future we're going to want to separate our animals into different types like predator and prey so we're using this as a sort of Base Class to base our predator and our pre um scripts off of so we're just going to do public uh protected navesh agent uh nav mesh agent the locase in and then we're going to do protected animal State and we're going to call this our current State and equal this to be um animal State idle like so we're going to go ahead and create a void start private void start and we're going to call a function we're about to create called initialize animal so now what we're going to want to do is actually create this initialized animal function so coming beneath our void start we're going to create a protected virtual void and this is our initialized animal function so nav M agent equals get component nav mesh agent then beneath this you're going to want to go NAB mesh agent speed which is the one we just um got now much agent speed is equal to walk speed so essentially what we're doing here is just grabbing the required components off of our um game object and just set setting up the variables within that benath this we're just going to go and make sure that current state is equal to the animal State idle and then beneath this we're going to call in update State function which again we're going to have to create an OTE so beneath this we're going to go ahead and create our update State um function so we're going to do again protected virtual void and call this update State then we're going to go ahead and create a switch for our enum this our current state case animal State idle and then beneath this you're going to want to type in handle idle State this is going to be again another function that doesn't exist yet and then we will break out of this once more we're going to do case animal State moving handle moving State again another function doesn't exist and then we will finally break out this sorry I forgot to put my P on on the end of that but these two functions obviously don't actually exist yet so what we're going to do is just create two more protected virtual voids this is our handle idle State and just going to copy and paste this and change this to be our handle moving state so we're going to set these two functions up in just a moment but the first thing we're going to want to do is actually create a function to choose a random Point nearby the animal that the animal can actually move towards so we're going to create a protected Vector 3 get random nav mes position and this is going to take in a vector 3 called origin as well as a float called distance so what we're going to be doing in this um function is we're going to create a vector 3 point that our animal can move to within its current position and the distance given to it so the first thing you're going to want to do is obviously create a vector 3 so we're going to call this Vector 3 random direction is equal to random do inside unit sphere times distance like so this is going to create a random Point within the um specified sphere the sphere has a radius of one and we're just timesing it by distance to give it a larger radius to pick from then we're going to take our random Direction variable and we're going to just do random Direction plus equals origin so it starts from its or origin position then finally we're going to do nav mesh hit and call this our nav mesh hit that's it for these variables we're then going to start some proper code so the first thing we're going to do is try and find a valid position on the ne on the nav mesh so we're going to do an if nav mesh nav mesh. sample position and the sample position is going to allow us to actually double check that we are allowed to move towards this position from where we currently are or where the animal currently is so we'll typeing in random Direction com out NAB mesh hit and distance and finally we're just doing nav mesh do all areas then we're just going to do return nav mesh hit start position so if we can move towards this position we will return the nav position that we have created that's what we do if we cannot move to the position that we we tried to move to we're going to recall this get random nav mesh position from within the function just going to return get NV M position or get random n m position and just type in origin distance so in other words we just retry and recursively until we get a valid position to move to now we're going to move on to our handle idle state so the way we're going to handle our idle States and our moving States and stuff like that is with I numerators which is a co- routine which will allow us to do things like waiting for a certain number of seconds before we do a certain Behavior this will just make it easier it will also mean that we don't have to use an update so it'll be better in terms of performance for our animals so what we're going to do is type in start Co routine and we're going to call a function called wait to move we're then going to come beneath this and create a private I numerator and call this wait to move which is the function we just started here what we're going to do in here is create a random wait time so float going to call this wait time is equal to random range or random do range rather open this up we're going to do our idle time which is the variable we created up here which is currently set to be 5 Seconds we are then going to divide this by two then do comma and idle time time 2 this will just give our animals a bit of a more random movement if we have like five animals starting at the same time it might be nice for them to start moving at different times just to create a more realistic environment then we're going to do something which is yield return new wait for seconds and then pass in this float that we just created called wait time inside of some brackets this is essentially just going to wait for whatever this is so if it's about 5 seconds on average it will wait for 5 seconds then it will continue the code so whatever we put down here will happen after wait time has been elapsed so what we're doing here is Vector 3 and we're going to call this our random destination and we're going to equal this to get random nav mesh position for our origin we're passing in transform dot position and for our distance we're passing in our Wonder distance variable so this is essentially getting a random position using the function we created earlier after waiting which is our idle State we're now moving towards our moving state so we're getting our random position then we're going to navesh agent do set destination Open Bracket and we're going to type in random destination which is the variable we just created so what this is doing is grabbing our nav match agent from our animal and giving it the destination to move towards and the navm will take care of everything else it will take care of um avoiding obstacles stuff like that it will just try its best to move towards that position we're then going to call another function here I'm going to do two little Lines Just because with this function doesn't exist yet and we're not going to create it for a while so it's set State Open Bracket animal state. moving so this is going to be used to set our states to a new or set our current state to the moving state but the first thing I wanted to do is actually set up our handle moving State as well so again in this one we're doing another coroutine so start co- routine and then we're going to just call this our weit to reach destination this is all we're doing in our handle moving State function we're then going to create another private I numerator and call this wait to reach destination and all we're doing in here is making sure that we have reached our destination before we go back to our idle state so the first thing you want to do is type in float start time is equal to time. time this is going to record the current time in the game to ensure that we can break out of our movement if we haven't reached our destination within the time frame specified by our Max walk time so we're going to do while nav mesh agent remaining distance is bigger than navish agent. stopping distance we're going to do yield return null so what this basically means is every time we get to this point um without meeting these requirements where we are close enough to actually move to our back to our idle State we're going to loot back around and we're just going to keep waiting and waiting and checking and once we finally have reached the um destination that our animal is moving to we can run some other code there's one thing we're going to want to do above our yield return though which is actually double check that the time that has elapsed since we started walking hasn't gone above our Max walk time so to do this we're going to just do if time. time minus start time is smaller or equal or sorry bigger or equal to Max walk time we're going to open this up we're then going to just do nav M agent do reset path then we're going to do set state which is again the function we haven't created yet so again I'm going to there two lines in front of this set state animal state do Idol and finally we're just going to do a yield break so what this is doing essentially is making sure that the time that we've been moving for hasn't gone above our Max walk time if it has we're going to reset the nav agent's path so it'll stop moving set the state back to idle and break out of this I numerator one last thing you going want to do here is underneath our while we're just going to again set our states back to the idle so we can just copy and paste this with the two lines in front this basically means that our destination has been reached so if you want to do anything specific when your destination has been reached by the animal you can do it there now now we're almost done but obviously we still have these set State functions that are not being cooled so I'm going to go ahead and create a protected void and call this set State and inside this we're going to take an animal State and just call this new state and we're going to open this up inside of here we're going to do if current state is equal to New State or equal equal to New State we are then going to return so we're going to break out this function otherwise we're just going to do current state is equal to New State and then we're going to call a function called on state changed and we're passing in New State on state change is the final function that we're going to be creating today so again we're going to do a protected virtual void and on state changed and this is again going to take in an animal State called New State and what we're going to do inside of here is just is call our update State function which is the switch that we created up here the reason we got it set up for like this is um if you want to have specific things that happen when your state changes like animation changes and stuff like that we can do that within here however I recommend waiting for the next episode where we split this animal into prey and Predator because we will actually be overriding certain functions to have different behaviors based on the animal but now however we're just going to come up here and get rid of these comments on our set States and that should be it in terms of the programming today coming back to our scene here we are going to select our um our sheet with our nav mesh agent and our animal script already added we're going to set up our variables obviously I've set mine up how I like them but if you want your animals to be able to move further um have a longer Max walk time different speed and so on you can do that here idle time just means how long it's going to wait for so we're going to set this to be about 3 seconds just so we can get a better feel for what's going on and I'm going to go ahead and click play as you can see our sheep will snap down onto the terrain that's controlled by our navage agent and if you select the Sheep you can actually see its destination where it's going and stuff like that can see our animal is now in its idle state it will wait for 3 seconds once those three seconds are up it'll pick a new position to move towards and there it goes so that is everything for today's episode I hope you have enjoyed um in future episodes we'll be covering stuff like rotating the models to fit the terrain and a bunch of other stuff like that so please stick around make sure you subscribe and leave a comment if you've enjoyed thank you so much
Info
Channel: HawkesByte
Views: 3,875
Rating: undefined out of 5
Keywords: Unity, game, animal, AI, 2022, 2023, tutorial, how-to, animal AI system, spawner, NavMesh, navigation AI, wander, prey, predator, artificial intelligence, source code, free, Unity3D, Unity tutorial, game development, C#, coding tutorial, Unity NavMesh, game design, character AI, pathfinding, Unity project, game programming, behavior tree, Unity engine, game AI development, open-source, coding tips, game AI programming, Unity game design, game scripting, tutorial content, Unity ecosystem
Id: DBf2OvuVy8Y
Channel Id: undefined
Length: 19min 41sec (1181 seconds)
Published: Mon Jan 01 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.