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.
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.
@@tadpoleinseaofminnows8587 while trying to do as you suggested I get an error: "NullReferenceException: Object reference not set to an instance of an object"
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*
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.
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
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
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?
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
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
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.
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?
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
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).
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.
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?
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.
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.
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?
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.
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.
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(); } }
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?
@@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
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)
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
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
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.
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!
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
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.
8:00 you need to select 2D physics and to also select your Obstacle Layer mask if anyone is wondering.
its pretty straight forward ngl
Thank you!
You saved my time. Thank you very much.
Thanks Alot
Thx, Bro
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.
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.
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.
@@tadpoleinseaofminnows8587 while trying to do as you suggested I get an error: "NullReferenceException: Object reference not set to an instance of an object"
@@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.
@@Gomperk I can post my code. I don't think it is to big for the chat.
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*
You are godsend
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.
The "refresh button" you are referring to at 8:50 is the 'Scan' button, right above 'Add Component' on the bottom.
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
Thank you so much!
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
@@pixelcat4878 same bro, i really needed this lmfaoo
how do you get the grid to recognise the ground objects if you're not using a tilemap?
keep getting the error enemy updatepath couldnt be called?
Man you are my saviour
Awesome video, helps a lot with simple enemies and also with flying enemies (like Bats 🦇)
For smooth moving you can use:
private Vector2 currentVelocity;
rb.velocity = Vector2.SmoothDamp(rb.velocity, force, ref currentVelocity, 0.5f);
against:
rb.AddForce(force);
Thank you! This works perfectly
@@Alien808OCF I am glad to help :)
body does not exist in current context
@@theredsparrow4882Do not use body use rb, or whatever your variable is called
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?
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
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
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.
OMG thanks for this fully functional AI :)
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?
Did you find a solution?
@@Marc-ek6gf yes i made a new script without A* where is 2 invisible borders where is the enemy can move. and it works
:)
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
Someone could help me? I can't drag the player into the target transform field
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
Also my enemy is floating and standing still and whenever i get close to him the error i typed above appears.
Did you solve it?
I fixed the problem adding the seeker script
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).
A little late but it's not working for some reason
I am unable to actually bake my tilemap, what exactly am I missing?
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.
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?
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.
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.
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?
i'm not sure, but instead of addforce using Vector2.MoveTowards() will help you.
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
Hi how can you make the enemy has 2 targets. so I can make like a patrol behaviour thing. thanks
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.
Add this for not levitation while jump
// Movement
if (!isGrounded) force.y = 0;
rb.AddForce(force);
Awesome thanks for improving it! If you want you or someone else can make a pull request on github for it!
i add it and he still can fly
@@xikosantos8074 check the rigidbody settings for gravity...maybe u find solution.
@@sujit5872 nah i didnt find any
he still levitates
@Djordje Grbic I think he added it right where it says //Movement
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.
I have that and still get the error
@@ea1766 same, did you figure it out?
@@chandlerrenteria9043 select 2d physics in inspector for the path finder object u put the script on.
Hi, I know this is kind of late but will this work on a non grid based game?
Yes it will work
its soo awesome to see my Enemies work with a* thanks a lot :D
In my case the grid would change in real time, Idk how that would work
probably add a logic to your level the 'rescans' the level every so often... I don't know how labor intensive that might be.
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();
}
}
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?
Maybe you could use a colllider as a trigger
remove that flip what this mean how to remove that red points
it doesn't work man please help me ;(
am stuck twice week form other code so I'll pass my AI class becuase you thank you
It's not working for me
Will be back when I'm in the AI creation part
@Yunus Demirelli I didn't.. I don't need it anymore
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.
nwm, I solved it. Anyway good video :)
@@_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()
@@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
@@_mrcreep_3539 How did you solve it
@@Hoobis 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
How confusing it is that you write inconsistently.
Thank you so very much. May the Lord bless you always.
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)
hm post script here
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
perfect
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
The speed is three degrees.
it just flys everywhere xD its too OP for an AI
@@nagybalint1474 Did you set the speed up to 3?
he cant jump anymore pls help
@@reelo7931 Did you check jump enabled?
You are a menace
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.
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!
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
i guess i'll have to code it myself
@@praised_goodness someone else left a comment adding some additional code that I think fixes this.
@@Etredal It didn't
What pathfinding software are you using?
Astar (ik i am late :))
10:55
look this guy has windows 11's centered taskbar on windows 10 all the way back in 2020 lol
The designers of w11 were inspired after watching this video xD
@@Etredal ahaha xD
i love you
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
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.
this tutorial is extremely hard to follow
Copy past ım new ı realy understand nothind ew
This ISN'T advanced enemy AI ! This is the basic stuff, Advanced enemy ai is patrol, attack and flee.
Let the man have his clickbait, because god damn this video saved me
15:13