Knockback NavMeshAgents using Physics | AI Series 51 | Unity Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're going to look at one way to apply knockback to your enemy AI who are using a nav mesh agent this can apply to guns this can apply to explosions or even a melee attack hey Chris here from LL Academy here to help you who me yes you make your Game Dev dreams become Reality by helping you make your players even more powerful with a knockback effect and we're going to be using a physics-based knockback on our enemy AI with a nav mesh agent you might be thinking Chris you can't use the physic system and the nav mesh agent at the same time and you're right you can't but the process of applying a physics-based knockback to a nav mesh agent is relatively straightforward when we consider that we cannot use the systems together so all we need to do is disable One enable control of the other one and then switch back whenever we're ready what that means is we can have a rigid body that's marked is kinematic and have gravity turned off attached to a nav mesh agent along with a collider if we make the collider slightly smaller than the nav mesh agent radius that makes it so we can have our physics looking similar to the nav mesh agent moving around and having the obstacle avoidance working still on the nav mesh agent whenever we need to push back the nav mesh agent and we're going to be using a shotgun in this example whenever that happens we disable the nav mesh agent enable the rigid Body by turning off is kinematic and turning on use gravity apply a force to the rigid body and then we can use whatever logic we'd like we're going to wait for the rigid body to stop moving and then set the rigid body is kinematic false disable gravity reset the velocity just in case warp the nav mesh agent to that location that they're at now after they've been knocked back and then reenable the nav mesh agent and while that sounds like a lot of steps that's literally the entire process I've chosen in this video to use the gun Series so we have a gun system so we can shoot our nav mesh agents back if you haven't watched a lot of the AI series or the gun series before that's okay I'm going to talk about most of what you need to know in this video if you want to learn more about some specific topics that maybe you didn't understand in this video of links in the description to the AI series and the gun series videos that are most applicable to what we're talking about today but if you haven't watched the gun series and you're like I just want to apply knockback effect that's okay I'm going to talk about how you can apply this more generically than the specific example we're talking about here let's jump in and check out the scene let's start with our enemy AI we've got this llama that's going to be our enemy on here animator is not super important but you can play different animations like a get hit animation something like that we're not going to handle that in this video because we did a main response animation in the gun series and I'll link to that video in the description you can use the exact same thing here got a nap mesh agent not anything super important here just that the radius should be slightly larger than the collider so I have a capsule collider with 0.5 radius our obstacle voidance radius should be slightly larger than that capsule also a nonzero stopping distance is very helpful in fact we should probably increase this to about the radius we want a rigid body with is kinematic is true because a nav mesh agent will be driving where this rigid body moves whenever we apply the knockback this is kinematic will be flipped this is a heavy llama 75 kilos with some drag and some angular drag the mass that you put here will influence the force you need your guns to apply so if you use a mass of one which is the default you'll need to use much smaller Force values than what we're going to see here so we also have a capsule collider it should just be a normal collider ideally will be on the enemy layer as well again the radius should be slightly smaller than our avoidance future chis here an important piece of our collider is the physics material we can apply friction and bounciness to our colliders so whenever they collide with some object they will bounce more or less and slow down faster or slower higher friction means that they will slow down from the knockback push much faster higher bounciness will make them literally bounce off the walls our floor and any walls can also have different physics materials that have different properties to really control how this knockback effect works as we slide over different objects for example if the enemy AI is standing on ice this ground friction would probably be very close to zero but standing on something like dirt or conrete would have a much higher friction value like one the values we'll use are one on the ground material for both Dynamic and static friction zero bounciness and on the Llama will have point4 Dynamic and static friction and zero bounciness but of course feel free to play with these in your own game and you should also have some kind of movement script and that's where we're going to apply the knockback is within our movement importantly for this video we also have a enemy player sensor that whenever the player comes within this trigger collider the sphere trigger collider the llamas will start chasing the player and that's just to get them to group together so we can apply some cool knockback effects to a group of llamas that's really the only important pieces of this we've already baked a nav mesh and we've got a player that can oh let's just click play and we've got a player that can shoot like with shotguns you a lot of times have some kind of a knockback effect so that's what we're going to implement today you know here at LOM Academy this channel is all about education teaching you how to make your Game Dev dream become a reality that's why I want to talk to you today about this video sponsor Southern New Hampshire University or snhu Southern New Hampshire university offers lowcost online degree programs for both computer science and game design and development both of these are accredited degree programs that means you're going to be learning important information about how to do programming how to do game design how to do 3D modeling and much much much more courses at snhu are taught by professors with real world experience and when you graduate snhu will help you with your job hunt this is a great opportunity for you to really dive into a structured approach to learning programming and game development I went to college and graduated over 10 years ago I feel like this was a really important step in my game Deb Journey because now I have a really good foundational understanding of a lot of different concepts that we use routinely in game development even some of the courses I was like why the heck am I going to take this like linear algebra calculus 3 I find myself having to use especially on this channel so if you're interested in going to college and getting a good foundational understanding of all of these topics that we talk about here at LL Academy over to snhu.edu Lam Academy fill out the contact form there and a real person will get back to you to talk about which degree program is right for you again that's snhu.edu Lam Academy it's the first link in the description fill out that contact form and get started on your college degree so if we want something to be knocked back something I like to do is to make an interface so we can apply that to any type of object not just the one object we want to hit and since this is an impact effect and I'm using the same gun system from the gun series I'm going to add that to the impact effects folder something like I knockback make sure to make that an interface for this interface we just need one function get knocked back and that should accept a vector 3 with the force that we would like to knock back this thing with and then either with your gun or your bullet whatever you have that does the impact on whatever ends up getting hit you're going to want to call that get knocked back so from the gun series we have this handleable impact which is called whenever the bullet hits some object it plays some surface impact effects like particle system sounds whatever it applies some damage and then has some kind of collision Handler and we could probably have used this Collision Handler for the knockback but I think this way it will be just a little bit easier to understand using the ey knockback aable because you probably don't have all of this stuff but if you do and you've been watching the gun series I challenge you to go ahead and implement this using the ey Collision Handler instead of the ey knock back now after we've apply damage let's apply the knockback so we can just try if hit cider try get component out I knock back aable knock back aable what we're going to want to do is apply that Force right so knock back aable get knocked back with some Force but how do we know what that force is well because we're using the gun system I went ahead and made a knockback config scriptable object with which just holds what kind of strength we should apply so the knockback strength and some kind of distance falloff if you're not using this system you can set this up on your gun or your bullet however you configure how does this gun shoot or how does this bullet apply damage you can put this in that same place so if we check that out in the unity editor we have a scriptable object called shotgun knockback config with a 25,000 force and a distance falloff where at Point Blank Range it's going to be full strength and it'll fall off relatively slowly up until 10 units away at which point we'll apply no knockback this way if something's really far away we don't apply the knockback we might think maybe more realistically the knockback effect would be more like this where it very quickly fall off but that's a little bit less fun so farther away we can still feel powerful knocking the enemies back you can play around with this curve of course and see what makes the most sense and most fun for your game so the key part of this is we're going to evaluate the distance fall off at however far away we are times the direction and the knockback strength so we're going to get some kind of force that fall falls off over the distance and it's going to have the direction that's passed in we'll come back to our gun scriptable object or wherever you're handling the bullet impacts so we can call knockback config dog get knockback strength provided the direction which we happen to have available as the hit normal we'll use the negative hit normal since in this function now we only have access to the hit normal and not the original direction if you have the original direction of where you did the rcast from that's probably what you like to use if you only have the raycast hit you can use the negative hit normal with hit. normal and the distance from hit. distance and if you have a bullet CU you're using rigid body physics you should have something like on collision enter in which case you can use the normalized impulse which should give you a pretty good value for that as well or you could use the Collision contacts the first Contact and get the normal of that and that'll also give you a relatively good value for you to use here now once we've gotten our knockback strength we can just apply that here to say hey knockback aable get knocked back back so now we need to actually get knocked back and that's going to be done in our enemy movement so the first thing we can do is make it implement the ey knock back aable which then we can implement the missing members well before we Implement that let's just take a little bit of look around at What's Happening Here in the enemy movement so on start this AI is going to just randomly roam where it's going to pick a random location on the nav mesh and just try to move to that location if it gets called stop moving for any reason it's going to stop our moving code routine and disable this agent we have an ability to be slowed down that's not really important for this so we'll skip over that this also handles when we see the player and when we lose the player that comes from that player enemy sensor we're going to stop moving and then start chasing the player whenever they come in range and whenever the player goes out of range we're going to just start randomly wandering again and when we're chasing the player we're just setting the destination to that player's position and waiting some time and then setting it again what we do there is not super important the important piece is that we have a move co- routine that will need to stop whenever we get knocked back so we stop trying to chase the player or stop trying to move now in your game game this is going to be the part that you need to figure out based on your movement what do you need to stop doing and how can you make them stop doing that so they can be knocked back since there's so many different ways to handle movement I can't provide specific guidance other than what I'm showing you here that it's really helpful if you have Co routines running and you can stop them to stop that behavior from happening okay coming back to the code we want to use the rigid body to move whenever we're getting knocked back that way it's controlled by the physic system so we need this to also require component type of rigid body we'll create a private rigid body rigid body and a sign that on awake then we'll come to the get knocked back the first thing we're going to want to do is stop the movement code routine then we're going to assign move code routine to a new code routine where we're going to be moving using the knockback we're going to start that code routine and we're going to call that function apply knockback and we're going to give it the force and in here that's where we're going to do all the movement related to what should we do and when should we reenable the nav mesh agent and I found that you usually want to wait one frame before you start doing any of this stuff just because sometimes there was some carryover from one of these other Co routines and you'd start getting some errors logged to the console we're going to want to disable the N mesh agent so we're no longer going to be moving around and no longer be tied to the nav mesh we want to enable rigid body use gravity and we want to disable rigid body is kinematic that way the rigid body now has control and should behave realistically we'll then add the force to this rigid body then we want the Cod routine to wait for some time before we reenable the nav mesh agent and have the nav mesh agent start doing whatever they were supposed to be doing which is most likely chasing the player we want to wait for the next fixed update if we don't wait for that fixed update sometimes the AI won't get knocked back because the force hasn't been applied to that rigid body yet so we can yield return a new wait until with an arrow function here rigid body velocity magnitude is less than 0.05 which since this is a magic number maybe we can refactor this out to be configurable in the inspector let's call it still threshold we'll make it a serialized private float still threshold give default of 0.05 and maybe give it a range from 0.001 to 0.1 anything higher than that and you'll probably be able to tell that they just stopped abruptly and it's not going to look very good if you want you can also do something like yield return new weight for seconds .25 so they are like stunned at the end of their knockback for a quarter second or you can just have them immediately Chase back either of these is fine depending on what you want for your game now once we've decided okay we're done being knocked back we want to basically undo what we did up here at the top we're going to want to reset the rigid body velocity and angular velocity just so we don't have any residual knockback effects for the next time then we want to disable gravity reenable is kinematic and then very importantly we need to warp the navmesh agent to our current position this tells the nav mesh agent that hey I've been moved without your knowledge you're now here so then they'll snap to the nav mesh at that location and then we can enable the nav mesh agent again I found that it's best way to frame before we start doing something after this and then what we can do is determine what should we do from here so if you're using a state machine or behavior tree you would use that to determine what to do from here since we're using something very simple here we're just going to check if the player's not null meaning they are within range we saw that on C player we assigned that transform so we'll know they're here and we set them to null whenever they're gone so if the player's in range we're going to set the move code routine to be start code routine Chase player otherwise we're just going to idly Roam and this segment right here is really the key piece of this we want to disable the Nish agent enable rigid body physics apply the force wait until we're done being knocked back disable the rigid body work the agent and then start doing whatever we wanted to do before so let's take a look at that over here in the unity editor we actually don't need to do anything to get this set up because we're using the enemy movement which is already there and we already applied the knockback effect in our gun and there we go our agent gets knocked back they do a little warp and then start chasing again now we can see sometimes our agents maybe their veloc doesn't fully reset and we can just throw our agents through one another so there's a few things that we still need to do part of our problem is whenever we see and lose a player we're going to try to start roaming or start chasing the player and the nsh agent may be disabled what we can do is just wrap these with if the agent's enabled to do that because it's possible for the player to enter or leave the radius while they're getting knocked back it's actually very probable depending on the force configuration you use that the player will go out of range so here's one thing that we can do and another is it might be nice if we have a Max time to wait before we start enabling because maybe our agents just have a really slow they just stay right above that threshold and we don't want them to appear broken never coming back so we can do a float knock back time setting to be time. time and we can check if our magnitude is less than the still threshold or the time. time is greater than knockback time plus Max knockback time and just in case you're not familiar with wait and tell what it does is it checks this deleg function every frame so we can wait and it'll check that this thing every frame whenever this delegate becomes true wait until we'll be done and we'll move on to the next line so let's set up a Max knockback time and let's set it to be like half a second or something because remember we're going to wait a quarter second as well so this gives us Max knockback time effectively is 3/4 of a second we have one more thing that before we go back I think would be really nice to see and that's what about having the agents push one another right now they can just fly right through each other or even get blocked by the other agents because the agents have a collider on them whenever we try to knock them back they can just get stuck which doesn't look very good so something we can maybe do is make a new script called knockback on collision and we want this to be a mono behavior that requires a component type of collider all this is going to do is on collision enter which is called whenever one collider collides with another collider if one of them has a rigid body we can say other. collider trigate component out I knock back aable knock back aable and then we want to call knock back a b. get knocked back with some Force but how do we know what force to use well there's this neat property called impulse on the Collision we can work out the total Force applied by dividing the total impulse by the last frames fixed Delta time which is exactly what we want to do we want to apply the force that I was just hit with to this object here much like earlier we want to use the negative impulse because the impulse is in the wrong direction it's in the direction that the other collider applied force to this object on this Collision so what we can do is on our preab for our llama we can add that knock back on collision then if we click play we get all these llamas to start chasing and just in case your enemies fly through one another still make sure that you have your enemies on a layer that collide with themselves so now we can see the llamas bump into each other and push each other back that's pretty cool I guess the last important thing to note is if your llamas or your enemies ever get too far off the nav mesh you can't warp them back so it's important to have some kind of way to keep them on the nav mesh and you can handle this in a few different ways one option could be every frame of that knockback you do nav mesh. sample position and make sure that the nav mesh agent doesn't leave the nav mesh another option is you could just design your levels where they can't be knocked off by putting in Clips or walls to prevent the navmesh agent from being pushed off and I'm sure you can come up with some other clever ideas that I haven't thought about so far this is something that's been requested a bunch of times on the Channel and I'm really excited to finally have gotten able to cover it if you want to learn more about how the shotgun was created make sure that you've liked and subscribed so you can stay up to date whenever I cover this on the gun Series in a couple of weeks if you haven't already checked out the gun series I highly recommend you check out that playlist we cover everything about having a highly customizable gun system using scriptable objects the full project for all my videos is available on GitHub for free for everyone if you think that's really awesome and you want to show your support for this channel go ahead and head over to patreon.com academy or click join or super thanks right here on YouTube that means a lot to me and it helps me out a ton if you don't have the money for that and you still want to show your support for the channel use the affiliate links down in the description to the asset store and Humble Bundle those give me a small percentage of the purchase price at no additional charge to you and that also helps me out tremendously and I want to give a special shout out to all of my supporters on patreon and YouTube your support makes this channel possible at the phenominal and the tremendous tier you get access to this super cool dissolve Shader that's exclusive to the support starting at the awesome tier you'll get a shout out at the end of every video like these awesome supporters Ivan rulan ifis Perry and Mustafa there also all of these great supporters as well thank you all for your support I am so incredibly grateful
Info
Channel: LlamAcademy
Views: 2,322
Rating: undefined out of 5
Keywords: Unity, Tutorial, How to, How to unity, unity how to, llamacademy, llama academy, video game development, development, ai series, unity ai series, unity ai, knock back, knockback, knockback enemy ai, knockback enemy, navmesh knockback, knock back navmesh agent, knockback navmeshagent, knock back navmeshagent, physics knockback, physics knockback navmeshagent, physics knockback nav mesh agent, unity navmeshagent knockback, unity nav mesh agent knock back
Id: 0NH5obeOb7I
Channel Id: undefined
Length: 19min 54sec (1194 seconds)
Published: Tue Jan 09 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.