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

  Рет қаралды 46,682

Etredal

Etredal

Күн бұрын

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...

Пікірлер: 134
@TheScorpionAly
@TheScorpionAly 3 жыл бұрын
8:00 you need to select 2D physics and to also select your Obstacle Layer mask if anyone is wondering.
@nagybalint1474
@nagybalint1474 3 жыл бұрын
its pretty straight forward ngl
@minestarplaysxD
@minestarplaysxD 3 жыл бұрын
Thank you!
@johnzuo8022
@johnzuo8022 2 жыл бұрын
You saved my time. Thank you very much.
@kashifnawaz8851
@kashifnawaz8851 2 жыл бұрын
Thanks Alot
@TheScorpionAly
@TheScorpionAly 3 жыл бұрын
Awesome video, helps a lot with simple enemies and also with flying enemies (like Bats 🦇)
@faanross
@faanross 2 жыл бұрын
The "refresh button" you are referring to at 8:50 is the 'Scan' button, right above 'Add Component' on the bottom.
@victormeas7898
@victormeas7898 2 жыл бұрын
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
@smallkloon
@smallkloon Жыл бұрын
Thank you so much!
@of3788
@of3788 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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.
@Oliver_Connell
@Oliver_Connell Жыл бұрын
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*
@jeremiahmauga1801
@jeremiahmauga1801 4 ай бұрын
You are godsend
@mrdanceroriginal
@mrdanceroriginal 2 жыл бұрын
OMG thanks for this fully functional AI :)
@DrFross09
@DrFross09 3 жыл бұрын
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 жыл бұрын
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 Жыл бұрын
@@pixelcat4878 same bro, i really needed this lmfaoo
@nagybalint1474
@nagybalint1474 3 жыл бұрын
its soo awesome to see my Enemies work with a* thanks a lot :D
@attenurmi936
@attenurmi936 Жыл бұрын
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.
@pippasoul4048
@pippasoul4048 7 ай бұрын
how do you get the grid to recognise the ground objects if you're not using a tilemap?
@Valikillenni
@Valikillenni 11 ай бұрын
Man you are my saviour
@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
@shellbox-studio5230
@shellbox-studio5230 2 жыл бұрын
For smooth moving you can use: private Vector2 currentVelocity; rb.velocity = Vector2.SmoothDamp(rb.velocity, force, ref currentVelocity, 0.5f); against: rb.AddForce(force);
@Alien808OCF
@Alien808OCF 2 жыл бұрын
Thank you! This works perfectly
@shellbox-studio5230
@shellbox-studio5230 2 жыл бұрын
@@Alien808OCF I am glad to help :)
@theredsparrow4882
@theredsparrow4882 Жыл бұрын
body does not exist in current context
@shellbox-studio5230
@shellbox-studio5230 Жыл бұрын
​@@theredsparrow4882Do not use body use rb, or whatever your variable is called
@dubble.
@dubble. 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 Жыл бұрын
A little late but it's not working for some reason
@oloy7038
@oloy7038 2 жыл бұрын
Hi how can you make the enemy has 2 targets. so I can make like a patrol behaviour thing. thanks
@Emerald_Dev
@Emerald_Dev Жыл бұрын
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?
@phunweng962
@phunweng962 3 жыл бұрын
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
@pressgforshout4439
@pressgforshout4439 2 жыл бұрын
am stuck twice week form other code so I'll pass my AI class becuase you thank you
@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.
@tobiasbn2005
@tobiasbn2005 23 күн бұрын
hey i basicaly copied the script word for word but my private Path path always seem to be null and honestly i have no idea when its supposed to get set as something
@rodrigocortez2770
@rodrigocortez2770 4 ай бұрын
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
@nootherkyle
@nootherkyle 3 жыл бұрын
perfect
@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
@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
@Chuckzplace
@Chuckzplace 3 жыл бұрын
keep getting the error enemy updatepath couldnt be called?
@santiagosalamancamora2302
@santiagosalamancamora2302 3 жыл бұрын
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.
@icecoyote764
@icecoyote764 Жыл бұрын
Someone could help me? I can't drag the player into the target transform field
@makled
@makled 2 жыл бұрын
I am unable to actually bake my tilemap, what exactly am I missing?
@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
@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.
@beetal3850
@beetal3850 2 жыл бұрын
Hi, I know this is kind of late but will this work on a non grid based game?
@Gurseerat_Singh
@Gurseerat_Singh 2 жыл бұрын
Yes it will work
@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(); } }
@eragon2287
@eragon2287 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 :)
@oxfa7958
@oxfa7958 3 жыл бұрын
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 3 жыл бұрын
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
@devedeveloper1248
@devedeveloper1248 2 жыл бұрын
it do your exacly code but it dont work pls can you help me? :(
@renatusdev
@renatusdev 3 жыл бұрын
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.
@mileselectric3677
@mileselectric3677 11 ай бұрын
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 11 ай бұрын
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 11 ай бұрын
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.
@MiguelHernandez-zd9mp
@MiguelHernandez-zd9mp 3 жыл бұрын
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 3 жыл бұрын
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!
@scrapy7806
@scrapy7806 3 жыл бұрын
remove that flip what this mean how to remove that red points
@MrGoldorange
@MrGoldorange 3 жыл бұрын
Add this for not levitation while jump // Movement if (!isGrounded) force.y = 0; rb.AddForce(force);
@Etredal
@Etredal 3 жыл бұрын
Awesome thanks for improving it! If you want you or someone else can make a pull request on github for it!
@xikosantos8074
@xikosantos8074 3 жыл бұрын
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 жыл бұрын
@@sujit5872 nah i didnt find any he still levitates
@xikosantos8074
@xikosantos8074 3 жыл бұрын
@Djordje Grbic I think he added it right where it says //Movement
@wonkanese
@wonkanese Жыл бұрын
You are a menace
@_mrcreep_3539
@_mrcreep_3539 3 жыл бұрын
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 жыл бұрын
nwm, I solved it. Anyway good video :)
@Etredal
@Etredal 3 жыл бұрын
@@_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 жыл бұрын
@@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
@ThiagoPrego
@ThiagoPrego 7 ай бұрын
Thank you so very much. May the Lord bless you always.
@random_precision_software
@random_precision_software 3 жыл бұрын
What pathfinding software are you using?
@laabedmedsami9357
@laabedmedsami9357 2 жыл бұрын
Astar (ik i am late :))
@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)
@nagybalint1474
@nagybalint1474 3 жыл бұрын
hm post script here
@DayzeXzxR
@DayzeXzxR 2 жыл бұрын
How confusing it is that you write inconsistently.
@mmmosd
@mmmosd 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 жыл бұрын
he cant jump anymore pls help
@mmmosd
@mmmosd 3 жыл бұрын
@@reelo7931 Did you check jump enabled?
@laabedmedsami9357
@laabedmedsami9357 2 жыл бұрын
it doesn't work man please help me ;(
@eazzy000
@eazzy000 Жыл бұрын
It's not working for me
@praised_goodness
@praised_goodness 11 ай бұрын
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 11 ай бұрын
i guess i'll have to code it myself
@Etredal
@Etredal 11 ай бұрын
@@praised_goodness someone else left a comment adding some additional code that I think fixes this.
@praised_goodness
@praised_goodness 11 ай бұрын
@@Etredal It didn't
@emberdragons8244
@emberdragons8244 Жыл бұрын
i love you
@kapcapkapcap6104
@kapcapkapcap6104 4 ай бұрын
15:13
@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 жыл бұрын
The designers of w11 were inspired after watching this video xD
@XZYSquare
@XZYSquare 2 жыл бұрын
@@Etredal ahaha xD
@kapcapkapcap6104
@kapcapkapcap6104 4 ай бұрын
10:55
@RejhanTrubljanin
@RejhanTrubljanin 11 ай бұрын
this tutorial is extremely hard to follow
@Wayloz
@Wayloz 3 жыл бұрын
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.
@serhattnc1815
@serhattnc1815 2 жыл бұрын
Copy past ım new ı realy understand nothind ew
@random_precision_software
@random_precision_software 2 жыл бұрын
This ISN'T advanced enemy AI ! This is the basic stuff, Advanced enemy ai is patrol, attack and flee.
@tastysausage6960
@tastysausage6960 2 жыл бұрын
Let the man have his clickbait, because god damn this video saved me
Pathfinding - Understanding A* (A star)
12:52
Tarodev
Рет қаралды 113 М.
2D PATHFINDING - Enemy AI in Unity
23:13
Brackeys
Рет қаралды 800 М.
Кәріс өшін алды...| Synyptas 3 | 10 серия
24:51
Китайка и Пчелка 4 серия😂😆
00:19
KITAYKA
Рет қаралды 1,5 МЛН
Creating SMART enemies from scratch! | Devlog
5:40
Challacade
Рет қаралды 259 М.
Platformer Pathfinding! - Devlog #1
6:20
Zachary Newsom
Рет қаралды 6 М.
Adding AI and Pathfinding to a Platformer
5:03
Steven
Рет қаралды 88 М.
31 portals of impossible shape
35:50
optozorax
Рет қаралды 614 М.
Extremely SIMPLE but POWERFUL platformer 'bloodhound' enemy AI
17:58
10 Unity Tips You (Probably) Didn't Know About
6:47
Sasquatch B Studios
Рет қаралды 33 М.
The PERFECT Pathfinding! (A* Pathfinding Project)
24:59
Code Monkey
Рет қаралды 109 М.
Pathfinding in Unity DOTS! (Insane Speed!!!)
24:56
Code Monkey
Рет қаралды 129 М.
Самая высокая малышка в мире 😳
0:39
УГОЛ СМЕХА
Рет қаралды 7 МЛН
Who reaches the finish line first ??
0:59
SS Food Challenge Junior
Рет қаралды 29 МЛН
Накачал Предплечья РИСОМ!
0:36
Илья Калин
Рет қаралды 8 МЛН
Choose the right bottle to win
0:59
Fun4Two
Рет қаралды 83 МЛН
СИМВОЛИЧНОЕ ИСКУССТВО
0:28
В ТРЕНДЕ
Рет қаралды 2,7 МЛН