Advanced AI in Unity [Tutorial] - Physics, Pathfinding, Editor Adjustments

Поделиться
HTML-код
  • Опубликовано: 10 май 2024
  • Today in this tutorial we create a fully functional AI system for 2D. This includes jumping, movement, activation and disactivation, and uses the A* algorithm. All of this is programmed in Unity and requires a basic knowledge of programming and Unity usage.
    Download the project: github.com/etredal/AdvancedAI...
    Please note that the first portion of this video repeats what is covered in Brackeys video: • 2D PATHFINDING - Enemy...
    For general information about my channel including music used: github.com/etredal/youtube-de...
  • ХоббиХобби

Комментарии • 133

  • @TheScorpionAly
    @TheScorpionAly 3 года назад +35

    8:00 you need to select 2D physics and to also select your Obstacle Layer mask if anyone is wondering.

  • @TheScorpionAly
    @TheScorpionAly 3 года назад +3

    Awesome video, helps a lot with simple enemies and also with flying enemies (like Bats 🦇)

  • @faanross
    @faanross 2 года назад +2

    The "refresh button" you are referring to at 8:50 is the 'Scan' button, right above 'Add Component' on the bottom.

  • @mrdanceroriginal
    @mrdanceroriginal 2 года назад

    OMG thanks for this fully functional AI :)

  • @victormeas7898
    @victormeas7898 2 года назад +4

    For anyone wondering, baking the grid is in the scan option at the bottom of the Component (named AstarPath) or can be called via script with AstarPath.Scan() in case you need to rebake it on runtime

  • @DrFross09
    @DrFross09 3 года назад +2

    This worked better for me than the brackeys tutorial.. I already don't like importing other assets, but gave this one a pass since there's no default 2D navMesh option. Honestly I want to apologize started this tutorial first, then noticed brackeys had one, I immediately stopped this video to go to his (because he's trusted), however his configuration didn't mesh with my character well. I then came back here. I will admit though it took me much longer than 24:40 to get this to work, but it finally did, Thank you for making this.

  • @yxshv
    @yxshv 2 года назад +24

    thanks a lot for this. i first tried doing this from brackeys video but i just couldn't get my AI to jump. and i wasn't satisfied with my enemy flying around

    • @chips7490
      @chips7490 Год назад +1

      @@pixelcat4878 same bro, i really needed this lmfaoo

  • @of3788
    @of3788 Год назад +11

    A couple small improvements I've made:
    even the new version of isGrounded which they have used allows the enemy to fly if there is any type of background which uses a collider because the raycast is able to hit that background and thinks the enemy is grounded. Additionally, the enemy will be unable to jump if it is too close to an edge because the raycast goes down from the centre of the enemy (meaning if less the half of it is on land the raycast will not collide with the ground and you will not jump.)
    Corrected line:
    RaycastHit2D isGrounded = Physics2D.BoxCast(col.bounds.center, col.bounds.size, 0, Vector2.down, 0.1f, groundLayer);
    This creates a box to check weather you are grounded instead of a line, fixing the issue stopping it from jumping near edges and uses the LayerMask 'groundLayer' to make sure it only counts collisions with the ground and not any backgrounds (make sure to include all objects you want to be able to jump on in a layer include).
    Feel free to check documentation for anything in the code I've written which you don't understand or just leave me a reply and I'll try to respond.

    • @lovfall642
      @lovfall642 Год назад +1

      Thanks a lot! I was trying to figure out what was wrong with the IsGrounded variable, and came back to this comment section as a last resort haha.

    • @tadpoleinseaofminnows8587
      @tadpoleinseaofminnows8587 Год назад +1

      In my script I used part of your script but did it a bet different and got nice up and down jumps. I have rigid body gravity set to 3.
      under the public class section, I also added:
      private BoxCollider2D coll;
      [SerializeField] private LayerMask jumpableGround;
      then in place of the video's raycast I used your script for the most part.
      RaycastHit2D isGrounded = Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0, Vector2.down, 0.1f, jumpableGround);
      doing it this way I have the speed set to 4 and the jump modifier set to 75.
      the jump mimics my characters perfectly minus the double jump ability on it.

    • @Gomperk
      @Gomperk Год назад

      @@tadpoleinseaofminnows8587 while trying to do as you suggested I get an error: "NullReferenceException: Object reference not set to an instance of an object"

    • @tadpoleinseaofminnows8587
      @tadpoleinseaofminnows8587 Год назад

      @@Gomperk you have to declare it. I integrated parts of the script and altered my code. You may have to play with it for a while.

    • @tadpoleinseaofminnows8587
      @tadpoleinseaofminnows8587 Год назад

      @@Gomperk I can post my code. I don't think it is to big for the chat.

  • @Chuckzplace
    @Chuckzplace 3 года назад +2

    keep getting the error enemy updatepath couldnt be called?

  • @Oliver_Connell
    @Oliver_Connell Год назад +5

    8:45 if you are using tileset, remember to set A* to Collider Type Point and set the right layer of your tileset to match in the Obstacle Layer Mask Within A*

  • @nagybalint1474
    @nagybalint1474 3 года назад

    its soo awesome to see my Enemies work with a* thanks a lot :D

  • @pippasoul4048
    @pippasoul4048 6 месяцев назад +1

    how do you get the grid to recognise the ground objects if you're not using a tilemap?

  • @Thrymbor
    @Thrymbor Год назад

    hi, do u maybe know how my enemy could walk up a 45° path? its get stucken in the corner on the bottom and the Node size is at 0.05

  • @oloy7038
    @oloy7038 2 года назад

    Hi how can you make the enemy has 2 targets. so I can make like a patrol behaviour thing. thanks

  • @makled
    @makled 2 года назад

    I am unable to actually bake my tilemap, what exactly am I missing?

  • @Emerald_Dev
    @Emerald_Dev Год назад +1

    Im gettin a weird error saying "ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" Anyone have any idea why this is happening?

  • @icecoyote764
    @icecoyote764 Год назад

    Someone could help me? I can't drag the player into the target transform field

  • @Valikillenni
    @Valikillenni 10 месяцев назад +1

    Man you are my saviour

  • @ea1766
    @ea1766 2 года назад

    NullReferenceException: Object reference not set to an instance of an object, i've done everything in the video even including putting the player as the target. The player in the Same Scene as the enemy too.

  • @shellbox-studio5230
    @shellbox-studio5230 2 года назад +3

    For smooth moving you can use:
    private Vector2 currentVelocity;
    rb.velocity = Vector2.SmoothDamp(rb.velocity, force, ref currentVelocity, 0.5f);
    against:
    rb.AddForce(force);

  • @phunweng962
    @phunweng962 3 года назад +1

    Will be back when I'm in the AI creation part

    • @phunweng962
      @phunweng962 3 года назад

      @Yunus Demirelli I didn't.. I don't need it anymore

  • @attenurmi936
    @attenurmi936 Год назад +1

    The reason your enemy is not moving horizontally well is likely due to its rigid body having drag and friction in it. Add a custom physics material to it to fix this. Playing around with the speed is not a good way.

  • @TopzicGaming
    @TopzicGaming 2 года назад

    I have an issue where my AI is trying to get on top of my player so the animation stays on run, how would I add a radius so my AI stops beside my player?

    • @drifter5680
      @drifter5680 Год назад

      Maybe you could use a colllider as a trigger

  • @beetal3850
    @beetal3850 2 года назад +1

    Hi, I know this is kind of late but will this work on a non grid based game?

  • @devedeveloper1248
    @devedeveloper1248 2 года назад

    it do your exacly code but it dont work pls can you help me? :(

  • @huseyinakkoc1062
    @huseyinakkoc1062 10 месяцев назад

    it is usefull mostly but how can ı udjust a body to seeker ? like normal AIpath 2d provides, now AI see every gap is a way

  • @santiagosalamancamora2302
    @santiagosalamancamora2302 3 года назад +5

    Hello, my pathfinder is working great except when the enemy is to close to the player, cause when that happens, my enemy slowers his speed a lot and it becomes to easy to kill. Any help pls? good video btw.

    • @Luturol
      @Luturol 3 года назад

      I'm having a similar problem. Because we are applying a force on rigidbody it may change if the distance is bigger or lower it's constant. how can we solve this?

    • @burakgidelim
      @burakgidelim 3 года назад

      i'm not sure, but instead of addforce using Vector2.MoveTowards() will help you.

  • @dubble.
    @dubble. 2 года назад +2

    direction.y gave some weird outputs for me and resulted in lots of bugs involving jumping. If anyone is experiencing this too, then I made a hacky fix for it.
    Instead of direction.y > jumpNodeRequirement
    I wrote target.position.y - 1f > rb.transform.position.y && targetrb.velocity.y == 0 && path.path.Count < 20
    Explanation:
    This code checks if the target position is above the position of the enemy (adding 1f to avoid excessive jumping in case it's a bit lower down on the y axis than the target). Then it checks if the velocity of the target is 0 (I do this to avoid it jumping while the target jumps, since that looks dumb). Then I check how many nodes away the enemy is, if it's bellow 20 it can jump (I do this to avoid it looking like a bunny, this could be used to make a banger of a bunny NPC).

    • @eazzy000
      @eazzy000 Год назад +2

      A little late but it's not working for some reason

  • @nootherkyle
    @nootherkyle 3 года назад +1

    perfect

  • @scrapy7806
    @scrapy7806 3 года назад

    remove that flip what this mean how to remove that red points

  • @rodrigocortez2770
    @rodrigocortez2770 3 месяца назад

    When the enemy is on a platform on top of the player, it doesn't ever go down the platform. How could I fix this? Instead it just goes from left to right not following the path

  • @eragon2287
    @eragon2287 2 года назад +2

    hello, Great video but for my it doesent working it typing in console:: Path failed: Computation Time 0,00 ms Searched Nodes 0. Error: Couldn't find a node to the star point. Please can you help me?

    • @Marc-ek6gf
      @Marc-ek6gf 2 года назад

      Did you find a solution?

    • @eragon2287
      @eragon2287 2 года назад

      @@Marc-ek6gf yes i made a new script without A* where is 2 invisible borders where is the enemy can move. and it works
      :)

  • @notica9648
    @notica9648 3 года назад

    it says
    NullReferenceException: Object reference not set to an instance of an object
    EnemyAI.PathFollow () (at Assets/EnemyAI.cs:63)
    EnemyAI.FixedUpdate () (at Assets/EnemyAI.cs:43)
    for me
    can anyone help me!!!!!!!!!!!!!!
    the error is here if (currentWaypoint >= path.vectorPath.Count) at
    // Reached end of path
    if (currentWaypoint >= path.vectorPath.Count)
    {
    return;
    }
    and here PathFollow(); at
    private void FixedUpdate()
    {
    if (TargetInDistance() && followEnabled)
    {
    PathFollow();
    }
    }

  • @pressgforshout4439
    @pressgforshout4439 2 года назад

    am stuck twice week form other code so I'll pass my AI class becuase you thank you

  • @oxfa7958
    @oxfa7958 2 года назад +1

    i keep getting this error
    NullReferenceException: Object reference not set to an instance of an object
    EnemyAI.UpdatePath () (at Assets/EnemyAI.cs:63)
    I did everything in the video i cant find whats causing the problem

    • @oxfa7958
      @oxfa7958 2 года назад +1

      Also my enemy is floating and standing still and whenever i get close to him the error i typed above appears.

    • @CR-dq1ch
      @CR-dq1ch 2 года назад

      Did you solve it?

    • @josue7156
      @josue7156 2 года назад

      I fixed the problem adding the seeker script

  • @renatusdev
    @renatusdev 3 года назад +2

    In my case the grid would change in real time, Idk how that would work

    • @DrFross09
      @DrFross09 3 года назад

      probably add a logic to your level the 'rescans' the level every so often... I don't know how labor intensive that might be.

  • @josue7156
    @josue7156 2 года назад

    For the people having problems with a NullReferenceException is probably because you are not using the "seeker" script , you need to add component and type seeker and add the script , not sure if its mentioned in the video but here is the fix.

    • @ea1766
      @ea1766 2 года назад

      I have that and still get the error

    • @chandlerrenteria9043
      @chandlerrenteria9043 2 года назад

      @@ea1766 same, did you figure it out?

    • @ea1766
      @ea1766 2 года назад

      @@chandlerrenteria9043 select 2d physics in inspector for the path finder object u put the script on.

  • @MrGoldorange
    @MrGoldorange 3 года назад +6

    Add this for not levitation while jump
    // Movement
    if (!isGrounded) force.y = 0;
    rb.AddForce(force);

    • @Etredal
      @Etredal  3 года назад +1

      Awesome thanks for improving it! If you want you or someone else can make a pull request on github for it!

    • @xikosantos8074
      @xikosantos8074 3 года назад +1

      i add it and he still can fly

    • @sujit5872
      @sujit5872 3 года назад

      @@xikosantos8074 check the rigidbody settings for gravity...maybe u find solution.

    • @xikosantos8074
      @xikosantos8074 3 года назад +1

      @@sujit5872 nah i didnt find any
      he still levitates

    • @xikosantos8074
      @xikosantos8074 3 года назад

      @Djordje Grbic I think he added it right where it says //Movement

  • @mileselectric3677
    @mileselectric3677 10 месяцев назад

    umm my enemy wont stop jumping. its just tiny hops and it wont move forward without them and if i adjust the jump height itll jump higher but still wont move without jumping.

    • @mileselectric3677
      @mileselectric3677 10 месяцев назад

      i figured out the problem but havent found a solution. basically the path starts in an upward position so the ai will always try to jump before moving instead of just moving forward. im not sure how this got adjusted or how to adjust it but im guessing the path should always go forward first and only make a path going upward if the target is above the enemy. how can i fix this?

    • @mileselectric3677
      @mileselectric3677 10 месяцев назад

      edit*** i changed the value of points on A* which helped it work great. my map though is huge and it seems any time the position of the enemy goes below 0 on the y axis it gains the ability again to jump for no reason still testing but this is what i found.
      edit**** its not that it goes below zero that it happens but a change in elevation in general causes it no matter if it spawns bellow or above center the line that the ai is trying to follow always wants to try and go towards the center to reach the player.
      edit***** so the grid no matter what has to cover a large area the problem was that i cannot make the grid as large as i would like. basically when i try to set the grid to a high number for example 2000 by 2000 it changes the node size on its own also width change effects depth and then causes the node size to change instead of allowing me to just alter and adjust the size of the grid graph.

  • @laabedmedsami9357
    @laabedmedsami9357 2 года назад

    it doesn't work man please help me ;(

  • @pranjalmaithani3383
    @pranjalmaithani3383 2 года назад

    Exactly what I was looking for. One thing I found was instead of the grid graph in 'pathfinder' we can also use a point graph to manually place nodes around the level, which would allow a more specific path per level and also be less in number. I believe this could be more optimized for a 2D platformer game
    There is more on the documentation page of A* as well

  • @_mrcreep_3539
    @_mrcreep_3539 3 года назад +1

    Hello, my enemies keep going on my starting position and not updating my currenct. Can you suggest where is the problem? Thanks a lot for video BTW.

    • @_mrcreep_3539
      @_mrcreep_3539 3 года назад +1

      nwm, I solved it. Anyway good video :)

    • @Etredal
      @Etredal  3 года назад +1

      @@_mrcreep_3539 For anyone else having this problem it would probably be that you need to make sure you are updating the target in Update()

    • @TheDerppGaming
      @TheDerppGaming 3 года назад

      @@Etredal What do you exactly mean by updating the target in update(), double checked and my code is the same but it has that bug where enemies only go to where my player spawned

    • @TheDerppGaming
      @TheDerppGaming 3 года назад

      @@_mrcreep_3539 How did you solve it

    • @_mrcreep_3539
      @_mrcreep_3539 3 года назад +1

      @@TheDerppGaming I dont remember exactly how, but it was something dumb xD, i think i had to place PLAYER into searching position or something like that

  • @eazzy000
    @eazzy000 Год назад

    It's not working for me

  • @MiguelHernandez-zd9mp
    @MiguelHernandez-zd9mp 2 года назад

    Thanks for the video. Do you know if applying this kind of pathfinding is taxing on the software for a 2D a whole 2D platform level? Also any idea how to add animations and enemy shooting into this Enemy AI script? Noob here.

    • @Etredal
      @Etredal  2 года назад +1

      Good questions! This is taxing so you can make the squares bigger and also have it run less often. These settings are available to change however you want. You can search for Unity Animator Tutorial on youtube to learn about how to set up a good state machine for adding behavior for shooting and such!

  • @wonkanese
    @wonkanese Год назад

    You are a menace

  • @random_precision_software
    @random_precision_software 3 года назад

    What pathfinding software are you using?

  • @tem3608
    @tem3608 3 года назад

    Hey my Enemy is in fact detecting my player and it's position but it's not moving towards it? it's not even jumping or anything. (yes i did check gravity, jump force, speed)

  • @ThiagoPrego
    @ThiagoPrego 6 месяцев назад

    Thank you so very much. May the Lord bless you always.

  • @mmmosd
    @mmmosd 3 года назад +3

    Thank you very much for using your project. But it looks better to change the movement like this
    rb.AddForce(Vector2.right * direction, ForceMode2D.Impulse);
    if (rb.velocity.x> speed)
    {
    rb.velocity = new Vector2(speed, rb.velocity.y);
    }
    else if (rb.velocity.x

    • @mmmosd
      @mmmosd 3 года назад

      The speed is three degrees.

    • @nagybalint1474
      @nagybalint1474 3 года назад

      it just flys everywhere xD its too OP for an AI

    • @mmmosd
      @mmmosd 3 года назад

      @@nagybalint1474 Did you set the speed up to 3?

    • @reelo7931
      @reelo7931 3 года назад +1

      he cant jump anymore pls help

    • @mmmosd
      @mmmosd 3 года назад

      @@reelo7931 Did you check jump enabled?

  • @DayzeXzxR
    @DayzeXzxR 2 года назад +2

    How confusing it is that you write inconsistently.

  • @emberdragons8244
    @emberdragons8244 Год назад

    i love you

  • @praised_goodness
    @praised_goodness 10 месяцев назад

    I guess the enemy is levatating cuz the script doesn't have any thing do decide that the enemy is on ground he only put the raycastHit2d and nothing related to it

    • @praised_goodness
      @praised_goodness 10 месяцев назад

      i guess i'll have to code it myself

    • @Etredal
      @Etredal  10 месяцев назад

      @@praised_goodness someone else left a comment adding some additional code that I think fixes this.

    • @praised_goodness
      @praised_goodness 10 месяцев назад

      @@Etredal It didn't

  • @kapcapkapcap6104
    @kapcapkapcap6104 3 месяца назад

    15:13

  • @kapcapkapcap6104
    @kapcapkapcap6104 3 месяца назад

    10:55

  • @XZYSquare
    @XZYSquare 2 года назад

    look this guy has windows 11's centered taskbar on windows 10 all the way back in 2020 lol

    • @Etredal
      @Etredal  2 года назад +1

      The designers of w11 were inspired after watching this video xD

    • @XZYSquare
      @XZYSquare 2 года назад

      @@Etredal ahaha xD

  • @serhattnc1815
    @serhattnc1815 2 года назад

    Copy past ım new ı realy understand nothind ew

  • @Wayloz
    @Wayloz 3 года назад +1

    Sure this uses astar but you aren't teaching it, yet another plugin that hands it to you.
    EDIT: Even Brackeyes uses a damn plugin

    • @dubble.
      @dubble. 2 года назад

      If you want to learn something that is as math-intensive as a searching algorithm, you will probably have to do it yourself. I recommend reading through the Wikipedia, they even have the pseudocode for an A* algorithm.

  • @RejhanTrubljanin
    @RejhanTrubljanin 10 месяцев назад

    this tutorial is extremely hard to follow

  • @random_precision_software
    @random_precision_software 2 года назад +1

    This ISN'T advanced enemy AI ! This is the basic stuff, Advanced enemy ai is patrol, attack and flee.

    • @tastysausage6960
      @tastysausage6960 2 года назад +5

      Let the man have his clickbait, because god damn this video saved me