Hiding AI - Take Cover Behind World Geometry | AI Series Part 29 | Unity Tutorial

Поділитися
Вставка
  • Опубліковано 13 лип 2024
  • Learn how to make NavMeshAgents find valid cover spots from another target object. In this video we'll specifically use a Player, but this can be applied to hide from any object - a grenade for example. Together we'll create a configurable script that allows us to refine which objects are valid to hide behind, and exclude those that are not.
    We'll add the following possible configurations:
    ⚫ Layers of objects to consider for cover, and to hide FROM
    ⚫ Radius to check for objects to hide behind, and FROM
    ⚫ Size of objects to hide behind
    ⚫ Distance from object cover must be
    ⚫ How good of a hiding spot it must be to take cover
    ⚫ How frequently to check for new hiding/cover spots
    💸 Ongoing sales 💸
    ⚫ See all active asset sales on the Asset Store: assetstore.unity.com/?on_sale...
    ⚫ Save 25% off your first Asset Store Order: prf.hn/click/camref:1101l9QvC...
    ⚫ Save up to 50% on NEW Assets: assetstore.unity.com/?new_sal...
    👨‍💻 As always, all code from this video is available on GitHub: github.com/llamacademy/ai-ser...
    ❤ Believe in LlamAcademy's mission and have received value from the videos? Become a Patreon Supporter or UA-cam Member:
    ⚫ Patreon: / llamacademy
    ⚫ UA-cam Member: / @llamacademy or click the Join button on any video
    📚 Resources:
    ⚫ You can also check out AI Series Part 11 where we used the Dot Product to control enemy gaining line of sight of the player: • How to Make a State Ma...
    ⚫ C# Comparison Delegate reference: docs.microsoft.com/en-us/dotn...
    ⚫ C# CompareTo reference: docs.microsoft.com/en-us/dotn...
    As usual with the AI Series, we're using the NavMesh Components: docs.unity3d.com/Manual/NavMe... not the built-in navigation system.
    ----
    Most tutorials come from knowledge gained making survival.llama.software Llama Survival - a top-down zombie survival shooter for Android and iOS.
    I also have some Unity Assets (affiliate link): assetstore.unity.com/publishe...
    Some links may be affiliate links, which at no additional cost to you, gives me a small portion of the purchase.
    #unitytutorial #tutorialtuesday #gamedev #tutorial #unity #llamacademy #gamedevelopment #ai
    Chapters:
    00:00 Introduction
    02:18 Scene Overview
    03:12 PlayerInput.cs
    03:25 EnemyLineOfSightChecker.cs - Look for Targets to Hide From
    07:10 EnemyMovement.cs - Find Hiding Spots
    13:42 Hooking It Up
    14:23 Demo - Enemy Chooses Random Cover Spots
    14:49 EnemyMovement.cs - Distance-based Ordering
    15:58 Demo - Enemy Sometimes Sticks to 1 Wall
    16:22 EnemyMovement.cs - Adding Minimum Distance from Target
    17:07 Demo - Enemy Sometimes Chooses Too Small a Wall
    17:54 EnemyMovement.cs - Exclude Objects Based On Size
    18:27 Demo - Enemy Hides Effectively
    19:37 EnemyMovement.cs - Throttle Hide Coroutine
    20:04 Final Demo

КОМЕНТАРІ • 94

  • @melodysprout23456
    @melodysprout23456 8 місяців тому +3

    I never would have thought about checking line of sight in this way. Genius. Also, you give a very clear explanation of what the dot product is.

  • @ronigleydsonvilasnovas8067
    @ronigleydsonvilasnovas8067 2 роки тому +4

    I can't believe you did this! man you are awesome, it's even better to know that we can combine this with any type of game. Thanks for another tutorial.

  • @Temus_
    @Temus_ Рік тому +1

    Great tutorial, that's the one I was looking for to implement in game I'm working on. Thanks a lot!

  • @trav2186
    @trav2186 2 роки тому +4

    this channel is pure dank fire

  • @MonochromeChromosome
    @MonochromeChromosome 2 роки тому +2

    thank all that is divine for the advices on this channel - Chris, your videos are amazing :)

    • @LlamAcademy
      @LlamAcademy  2 роки тому

      Thank you 🙏 I really appreciate that 🤗

  • @mkax07
    @mkax07 Рік тому +1

    Instant subscription man, this video is absolutely insane!!! Thank you!

  • @PazzaarProductions
    @PazzaarProductions 2 роки тому +5

    Those little snippets you play whilst explaining what parts of the code are doing (like the dot product) are a really nice touch. Sweet video.

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      Thanks :) I feel like a little visualization helps to explain it better than just my words sometimes

    • @Maskeowl
      @Maskeowl Рік тому

      @@LlamAcademy um i cant make it work i test githıb version it works but icant make it work i am sure its about trigger and collision cuz script and layer and layer phsics are set corretly im sure also it would be cool if enemy had better path finding like choose safer path not the sortest

    • @Maskeowl
      @Maskeowl Рік тому

      it need a ridigbody for triggercollider chech inever knew that but it some times bugged out i look that target transdorm reference went missing when it buggs why it went mising ?

  • @MagicPigGames
    @MagicPigGames 2 роки тому +2

    Thanks for these. I've been having a heck of a time getting nav mesh agents to work, with root motion and some various AI logic. We'll see if I can get it working!! :D

    • @LlamAcademy
      @LlamAcademy  2 роки тому

      Good luck! I’ve never used root motion with a NMA but I can imagine the troubles!

  • @TheDarkfire9251
    @TheDarkfire9251 5 місяців тому +1

    This is a fantastic solution to this problem, but if you don't know Unity it can be a bit hard to understand. The main part of the algorithm is basically this:
    - Use a large round collider to find cover objects; these will have to be tagged with a separate physics layer to differentiate them from regular environment colliders
    - Filter the results; set minimum distance from the enemy the NPC is hiding from, check minimum cover height
    - Sort the results by distance to make sure the NPC picks the nearest cover
    - Use the navmesh to find the point nearest to the cover
    - Get the nearest navmesh edge (obstacles are always surrounded by them) to that point. The normal vector of this edge lets us check the angle towards the enemy, which tells if we're on the good side of the cover
    - If not, sample another point some distance in the direction opposite to the enemy and repeat the navmesh edge step. Repeat a few times if you have large cover objects.
    - Move to the found cover spot
    This can be used with enemies, grenades and probably more, although you will have to make the NPC choose what's the most important thing to hide from, or expand the cover angle check to test for several objects.

    • @LlamAcademy
      @LlamAcademy  4 місяці тому

      Thanks for writing up a recap! 🙂

  • @gabrielplourde6791
    @gabrielplourde6791 Рік тому +1

    Thanks dude. Amazing tutorial, explanation, and even source code.

  • @ivanm71
    @ivanm71 7 місяців тому

    Wow, that's a golden tutorial

  • @Anders2057
    @Anders2057 8 місяців тому +1

    hey bro thanks for you work really ☺☺☺☺

  • @NunSuperior
    @NunSuperior 2 роки тому +2

    I got it working. Using the navmesh normal is pretty neat, never would have thought of that. One thing I'm going to add is a raycast from the test hit point back to the target (player) to double check that the agent won't be seen from that position.

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      That's a good idea especially if you have holes in the mesh the agent is hiding behind!

    • @Maskeowl
      @Maskeowl Рік тому

      dued i cant make it work still for a room

  • @P0Omah
    @P0Omah 2 роки тому +1

    Fucking sick ass content dude. Packed with info but really nice and consise with out any useless fluff. The high level overview in the intro explaining the goal of the video was also well done. Looking forward to finishing work so I can check out your you channel properly.

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      Thank you! I'm glad you like the format and the content!

  • @randomability1
    @randomability1 Рік тому +1

    Can you cover how you would add this to the state machine? Do you need two separate line of sight checks, or can you incorporate the line of sight checking into the enemy line of sight checks from part 11? How could you have the Enemy pop out from hiding/cover to shoot at the player and then go back to hiding/cover?

  • @UNITYCODE
    @UNITYCODE 2 роки тому +2

    i lovve youu yess youu

  • @taniskannapurna8563
    @taniskannapurna8563 2 роки тому +1

    This is really gold man, Can we create a cover shooting system. Have you created any video on this? Thanks for the video.It was very helpful

    • @LlamAcademy
      @LlamAcademy  2 роки тому +2

      I have not made a cover shooting video, but if you're using the NavMesh - you can use the same concepts from this video to pick the spots and manage the AI state going into a "take cover" state then a "shoot player" state.

    • @taniskannapurna8563
      @taniskannapurna8563 2 роки тому +2

      @@LlamAcademy I will do that, I have watched lots of videos on AI but yours was real gold.
      Appreciate your work, man. waiting for the next videos.

  • @Blackd0nuts
    @Blackd0nuts Рік тому

    This video is extremely helpful! Thank's a lot for this!
    I was wondering how to implement a similar system but with Unity's terrain. In this case we can't check for colliders and just have to rely on line of sight I guess?

    • @LlamAcademy
      @LlamAcademy  Рік тому

      Thanks! The terrain should work basically the same if the NavMesh is generated based on the Terrain. Is there a specific use case that’s not working for you?

    • @Blackd0nuts
      @Blackd0nuts Рік тому

      @@LlamAcademy What I meant is if we imagine a situation where the AI could use the terrain itself to hide from the player (like hiding behind a hill/slope that stands nearby). The AI would need to know that if they go behing this slope he wouldn't be visible to the player. I guess this would require an entire new system than the one you implemented here.

    • @LlamAcademy
      @LlamAcademy  Рік тому

      @@Blackd0nuts Oh, I got it. Yeah this is based on world geometry blocking, so you'd have to do line of sight checks to check for slope for cover. This one relies on the NavMesh completely for finding those cover points

  • @mubashirjamal3030
    @mubashirjamal3030 2 роки тому +2

    Wow what an amazing videos, all your videos are really logical and problem solving. Sir this really helps a lot of game developers who are working on the AI type game. We really appreciate your efforts.
    Sir will you please make an another video on the problem I am facing. The problem is that let suppose we have a scene in which there is some nav mesh agents, they are moving randomly from one place to another. But sometimes two agents moving in opposite direction, they do not navigate properly when they collide face to face, they force each other to go first to there destination and get stuck for some short time. And this think really looks dummy AI agents. How we can improve this.
    Once again thanks you for you efforts sir.

    • @LlamAcademy
      @LlamAcademy  2 роки тому

      Thank you!
      For agents not running into each other - so far I haven't found a reasonable way to make them avoid each other using the Navigation System alone. I'll keep researching it to see if I can find a good solution and if I can, I'll definitely share it in the form of a tutorial!

    • @mubashirjamal3030
      @mubashirjamal3030 2 роки тому +1

      @@LlamAcademy Thank you so much for your honest reply sir, but one think i tell you, that you will find the solution, because i watched your videos these were really technical problems and you have solved them through your efforts. Thanks for helping us. Sir will you share your gmail with me, so i may contact you on gmail.

    • @LlamAcademy
      @LlamAcademy  2 роки тому

      Thank you :)
      And yes, you can email me at support@llama.software

  • @pascalb5908
    @pascalb5908 2 роки тому +1

    This is a highly valuable tutorial. Regarding inserting this as part of a state machine, I haven't been able to figure out how to deactivate the EnemyMovement script component (i.e, for when not in use). Or should a boolean be used at a certain place in one of the script to enable/disable the hide/take cover action? If so, where? :) Thanks!

    • @LlamAcademy
      @LlamAcademy  2 роки тому +2

      Thank you 🙏!
      For your question about integrating it with a state machine - the Hide behavior starts based on OnGainSight. Because of this, depending on how your state machine is set up, you have a few options.
      1. You could have your state machine provide to this script a boolean value of whether they should be able to hide or not. Then in HandleGainSight you can consider this boolean and check it every so often (every frame, every X seconds, something like that) and once it's true, start this hide behavior.
      2. You could have your state machine handle starting this hide behavior when it transitions to the new "Hide from player" state. In this case, you could just toggle this script AND the LineOfSightChecker GameObject enabled/disabled as the state changes to/from "Hide state" to any other state. You may need some slight adjustments to handle OnEnable/OnDisable but that should get you on the right track at least.
      I'm sure there's more options but these are the first two that came to mind!

    • @pascalb5908
      @pascalb5908 2 роки тому +1

      @@LlamAcademy Splendid, and thank you very much for your detailed suggestions (I decided to use no. 2 for the moment).

  • @onurdogan9914
    @onurdogan9914 5 місяців тому

    Nice video, thank you, But I can't this. Infact I did it but when start game , character's movements are dull. What can I do?

  • @turnrp
    @turnrp Рік тому +1

    Ive used so many of your videos for my game but I have two floors for this and even when my character leaves he just freezes so I have no clue I hope someone can help cause this is really annoying and I have little to no experience making ai.
    UPDATE:
    I moved him to my second floor which dosen't have a roof and it worked fine but if there is a roof involved it bugs.

  • @TheGoldenDragonDev
    @TheGoldenDragonDev Рік тому

    How would i go about allowing the enemy to shoot while in cover? I already have an attacking script but at the moment the position the enemy ends up in makes it wierd when it shoots. Also I how can i make it so when a piece of cover is to short, it would play an animation instead

    • @LlamAcademy
      @LlamAcademy  Рік тому

      For the first one, AI Series part 11 might help you where it covers how to implement a State Machine. For the second, probably the simplest solution would be to define a height that classifies the object as “short” and Raycast from that height a short distance to see if you hit a wall, if so, it’s too tall. If not, it’s short and you can shoot over it!

  • @joel-BB
    @joel-BB Рік тому

    I'm forgot to update my agents stopping distance since I had it set to like 8 before I implemented this and was wondering why the agent would just stop moving to cover and stand out in the open that was why!

  • @spikechu
    @spikechu 3 місяці тому

    How do I enable the Editor script?

  • @shaikhabdulbasit5717
    @shaikhabdulbasit5717 2 роки тому +1

    Liam, ur videos are great, and they provide some intermediate level programming, try considering giving them a suitable title and they might reach more people

  • @WelshGuitarDude
    @WelshGuitarDude Рік тому

    Can you cover ai vision cones like in commandos

    • @LlamAcademy
      @LlamAcademy  Рік тому

      I don't know about commandos specifically, but this includes the fundamentals of the enemy vision.

  • @maximdaigle
    @maximdaigle 10 місяців тому

    What if I wanted AI agents to find the furthest ones away? Currently, just inverting the comparer works except the agent gets crazy between two points and can't commit to one. Is waiting for the agent to reach his destination before taking a new decision the way to go or is there a better way? Thank you!

    • @LlamAcademy
      @LlamAcademy  10 місяців тому +1

      To choose anything except the closest one I think you would have to come up with an algorithm that weights the decision to choose a new hiding spot. How we did it here would be a good starting point, but you may need to consider things like the time since they last chose a spot, how far other options are from the current position, and any other factors that seem relevant. Using all of those you could smooth out the jitteriness you're seeing with the raw just "always go to the farthest point" selection.

    • @maximdaigle
      @maximdaigle 10 місяців тому

      Thank you! What I ended up doing is adding a boolean param that allows changing from where we calculate the cover. In this case, I allow it to be from the player's position, and inverting the comparison allows the agent to effectively find the furthest viable cover from the player

  • @bangagus1703
    @bangagus1703 2 роки тому

    Brother, can you make tutorial for hide and seek like game horror survival.....?

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      That'd be a cool series, I'll consider it

  • @farziverse4209
    @farziverse4209 9 місяців тому

    If this works, my life is set!

    • @LlamAcademy
      @LlamAcademy  9 місяців тому

      I hope it worked for you then 😃

  • @TheGoldenDragonDev
    @TheGoldenDragonDev Рік тому

    so when my playercharacter approaches the enemy, instead of, yknow, running for cover. Unity just freezes. How od i fix

    • @LlamAcademy
      @LlamAcademy  Рік тому +1

      Sounds like you didn’t yield return something in the Hide coroutine

    • @TheGoldenDragonDev
      @TheGoldenDragonDev Рік тому

      @@LlamAcademy yup that did seem to be the problem. I went to your code on the github page and cross referenced it with mine and you are right thanks

  • @ChadGatling
    @ChadGatling Рік тому

    I am not sure that cosine is doing what you think it is doing here. the cosine of 360 is -0.284. according to your description should it not be -1 in that case? I think what you really want is (-fieldOfView +90) /90 and then limit the fieldOfView to 180. Where 180 is directly behind the hider.

    • @LlamAcademy
      @LlamAcademy  Рік тому

      You need to be using radians, not degrees!

    • @ChadGatling
      @ChadGatling Рік тому

      Ahh yes I see now. I tried this but was still operating on the idea that 360 should be 0 so I didn't see it as right. Tho past 180 degrees it does break. Setting it to 360 is the same as setting it to 0. Also my method produces a linear interpolation whereas the cos method produces a smoothstep curve.

    • @LlamAcademy
      @LlamAcademy  Рік тому

      That’s a good point. I noticed later that the FOV was about double what was expected. Thanks for the information

  • @Maskeowl
    @Maskeowl Рік тому

    18:29 how i acn add that editor gizmo

    • @Maskeowl
      @Maskeowl Рік тому

      mine is not moving somereason i litrly copy the code from github idk why

    • @Maskeowl
      @Maskeowl Рік тому

      its move some times but on enemy movement player transform isnt correcct

    • @kyvu8778
      @kyvu8778 8 місяців тому

      I have a same question like you, did you solve it?

  • @shadowduck1234
    @shadowduck1234 Рік тому

    This video made me realize I don't know anything about programming

    • @LlamAcademy
      @LlamAcademy  Рік тому +1

      😅 sometimes we all feel that way

    • @shadowduck1234
      @shadowduck1234 Рік тому

      @@LlamAcademy tru im boutta study this video

  • @mohokhachai
    @mohokhachai 10 місяців тому

    When you add me in your hash map

  • @_-VIS-_
    @_-VIS-_ 4 місяці тому

    I got like a million errors. Bro I wasted 2 hours for it to bug tf out😭

  • @alejandrovargas8538
    @alejandrovargas8538 2 роки тому

    why does mine hides in front of me?

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      Try playing with the configurations, especially the hide sensitivity

    • @alejandrovargas8538
      @alejandrovargas8538 2 роки тому +1

      @@LlamAcademy thanks, I eventually figured out that the size of my walls were odd

    • @LlamAcademy
      @LlamAcademy  2 роки тому

      Glad you figured it out!

  • @mohamedmusthafa1057
    @mohamedmusthafa1057 8 місяців тому

    One question How did U learn This😅

    • @LlamAcademy
      @LlamAcademy  8 місяців тому

      I think somebody asked how to do it and I spent some time fiddling with it to figure out how to do this one. It's been a while so I don't remember exactly. In most cases I get an idea from somebody (another youtube video, a suggestion, or even a game), then with whatever I know today and some research I'll play around with it until I get something that works.

    • @mohamedmusthafa1057
      @mohamedmusthafa1057 8 місяців тому +1

      That awesome Dude , Now I implemented this Mechanism to My Game state machine enemy ai its working when When I copy Ur Same Walls paste into my project, Otherwise My Own Primitive Cubes and Other mesh Doesn't detect edge , it failed even 2nd Attempt even i try to change same meshcollider box collider works as well ,even my primitives baked by navmesh well and Correct layer and also i try to resize Ur walls it still work ,so i just try to copy that probuilder mesh filter component to my primitives now enemy just ignores those objects No more error i dont know whats happens background
      Edit: i fixed it By Making that Walls Position y = 0;

  • @pennaverdeful
    @pennaverdeful Рік тому

    The intro is a bit cringe, but the tutorial is amazing. Thanks!

    • @LlamAcademy
      @LlamAcademy  Рік тому +1

      😄 haven't seen a comment about the intro in a while, thanks for that

  • @godsunchainedgames2667
    @godsunchainedgames2667 2 роки тому +1

    Doesnt work, i move near the enemy and it doesnt hide at all, just hides at start but when i move near it doesnt look for cover

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      That sounds like maybe your physics layers are not set up the same as we did here to detect the player

    • @godsunchainedgames2667
      @godsunchainedgames2667 2 роки тому

      @@LlamAcademy you mean the layers? dont know what you mean by physic layers, i made a video showing how is my project ua-cam.com/video/G4yJo7y4UBY/v-deo.html

    • @godsunchainedgames2667
      @godsunchainedgames2667 2 роки тому

      @@LlamAcademy This is a video of how is failing to find cover for a third time ua-cam.com/video/LGeRSoLfsZ4/v-deo.html

    • @LlamAcademy
      @LlamAcademy  2 роки тому +1

      @@godsunchainedgames2667 I mean the physics layers as mentioned towards the beginning of the video: ua-cam.com/video/t9e2XBQY4Og/v-deo.html
      From your video I see that is not the problem. However, there are many missing components, I wonder if you have added the Navigation Components? I will check it out in more detail when I get home.

    • @godsunchainedgames2667
      @godsunchainedgames2667 2 роки тому

      @@LlamAcademy I tried it in unity 2021 instead unity 2018 and it works more times but ends failing anyways ua-cam.com/video/yOOCH_rNtGw/v-deo.html