Pathfinding (NPC Follows Player/Aggro Monsters) - How to Make a 2D Game in Java #40

If you want to learn how the A* algorithm works, please check:
• Step by Step Explanati...
In this video, we will implement a pathfinding algorithm so NPCs/enemies can search the path and reach a specified location/target.
What we do this time:
- Guiding an NPC to a different location
- Letting an NPC follow you
- Making monsters start attacking/chasing you
If you want to use my assets (images/maps/sound) that are used in this tutorial, here's the link:
drive.google.com/drive/folder...
Guidelines for using Blue Boy Adventure's code and assets:
docs.google.com/document/d/1q...
Timestamps:
0:00 Introduction
1:38 Creating Node class
2:50 Creating Pathfinder class
19:36 Letting NPC finds the path
35:03 Drawing the path on the screen
37:16 NPC follows the Player
39:06 Monsters get aggro and chase the Player
44:21 FINAL RESULT

Пікірлер: 149

  • @RyiSnow
    @RyiSnow Жыл бұрын

    Correction: At 9:56 I scanned the interactive tile array in the background tile scan loop but that was a bad move since the iTile scan gets done in every background tile loop. If you have a lot of iTile, this can cause a performance drop. We only need to scan the iTile array once to find out which is solid and which is not so it's better to do it outside of the background tile scan loop. Sorry for the confusion!

  • @forte2265
    @forte22652 жыл бұрын

    "all the slimes are chasing us, what are you gonna do old man" i love your videos and theyve been a great help as i get back into coding, i really appreciate you uploading these!!!

  • @unifiedvideos7971
    @unifiedvideos79712 жыл бұрын

    Hi Ryi your videos are a truly gem ! Everyone else moves to external libraries it amazes me you do all this in raw java ! I think since your already implementing some advance stuff you should take a look into behavior trees in order to reduce all those if else statements and just have a more clean and robust framework of events/behaviors if you or others are planning to expand and maintain the game ex: adding events, complex jobs, dynamic behavior etc behavior trees offer a lot in terms of modularity, reusability and are simple to read. Thank you for your immense contribution.

  • @misterdneh
    @misterdneh2 жыл бұрын

    This is great, I implemented a different idea in my game where if the player walks near a monster and gets to close the monster starts navigating to the player to try to attack them. I like this mechanic though I will have to use it in a section of my world! Great work master of Java game teaching!

  • @IgorNV
    @IgorNV2 жыл бұрын

    Thank you contributing to the game dev community!

  • @peacefuldeityspath
    @peacefuldeityspath2 жыл бұрын

    Thank You so much. now i can add more on to the 2d game and understand the simple libraries used in here. :D

  • @UnderArea51
    @UnderArea512 жыл бұрын

    Thank you so much for breaking A-star Pathfinding down!!!

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    You're welcome!

  • @catalinadavid5953
    @catalinadavid59536 ай бұрын

    Wow! I needed to do a project at uni where i had to implement an algorithm in a project! So i chose your game and thought i would implement A* on it- but you have a tutorial on that even!!! That is so awesome, thaank youu!!!!!!!!!!❤❤❤

  • @Brodstam8
    @Brodstam82 жыл бұрын

    loving the progress! keep it up (:

  • @laurenzfitzner
    @laurenzfitzner2 жыл бұрын

    Thank you for this really usefull video! An now that I finished my final exams I can finally work on my game again!

  • @julianbertignoll5323

    @julianbertignoll5323

    2 жыл бұрын

    i have them in 14 days

  • @thevicraft_
    @thevicraft_2 жыл бұрын

    Thank you for this wonderful tutorial! You are the best 😊😊😊😊😊😊😊😊😊😊!!

  • @juandebenedetti2884
    @juandebenedetti2884 Жыл бұрын

    I have only one word to say: AMAZING!

  • @momagi6039
    @momagi60392 жыл бұрын

    Thank you for the great content !

  • @bastlomainlan2095
    @bastlomainlan20952 жыл бұрын

    is it possible to make a Map on several layers ? for example to make a tree, be behind when you are above and in front when below thanks in advance and for your content

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    It is possible. You can draw tiles such as tree and wall as in the way we did for NPCs or monsters and check if player is above it or below it. And keep drawing other ground tiles such as grass and road with the current method (otherwise they can hide player's lower body).

  • @fabiogeronimo9578
    @fabiogeronimo95787 ай бұрын

    Excelente essa aula foi minha preferida :), estou te acopanhando desde a primeira parabéns.

  • @sabawaheed1142
    @sabawaheed1142 Жыл бұрын

    Hello Ryisnow, thank you so very much for showing how to implement pathfinding, it really helped me out. I have one question. My game has a LOT of objects around the world, and when the pathfinding algorithm runs, it checks every single object in the world to see if it’s solid, which causes my game to slow down a bit. I believe the algorithm should not check every object in the ArrayList, but only the objects near the pathfinder (monster). Do you have any idea on how I can implement this optimization?

  • @kevincolgan6651
    @kevincolgan66512 жыл бұрын

    Great stuff learned alot from you

  • @luissolis6689
    @luissolis66892 жыл бұрын

    Hi Ryi, amazing tutorial you've done an amazing job explaining everything in such a simple way! I do have a question though, how would you go about adding in a second playable character, like lets say you have blueboy then you get the option to change to greenboy(example) would you extend the player class and just change what greenboy would have or would you create a whole new entity? I'm trying to make a game that would have multiple characters but I was just wondering how you would go about it.

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    Never thought about it but I would probably make a SuperPlayer class which extends Entity and create Blue Boy and Green Boy as its sub class.

  • @luissolis6689

    @luissolis6689

    2 жыл бұрын

    @@RyiSnow That's what I was thinking! Thanks for the reply!

  • @knightking5735
    @knightking5735 Жыл бұрын

    Amazing video!

  • @Nikitosik_761
    @Nikitosik_7612 жыл бұрын

    Thanks a lot!

  • @michajurkiewicz5471
    @michajurkiewicz54712 жыл бұрын

    Thank you for continuing the series. Ryi, please tell me, what to do so that the NPCs do not follow me, but the enemies? Alternatively, how to turn it off?

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    Did you watch the video from the start to the end?

  • @michajurkiewicz5471

    @michajurkiewicz5471

    2 жыл бұрын

    @@RyiSnow Yes, and I think, now I now :D

  • @Mrtargi
    @Mrtargi Жыл бұрын

    Hello Ryi, your pathfinding algorithm explanation is a gold! I really like your solution, but anyway how can we handle not solid tiles but solid area for example. I have objects of length 2,5,11 tiles width and same about height, they have similiar solid area, so I understand that at first I should check how many tiles solid area takes and put it into array , then check it trough pathfinding , but it is really hard in realisation. I would appreciate any your hekp or suggestion!

  • @od1367
    @od13672 жыл бұрын

    Thanks !

  • @watchjimstube
    @watchjimstube10 күн бұрын

    hi Ryi. love the series you've made. So my question is, my monster cant go left and right during the pathfinding. it just freezes and looks to be spinning in circles. How can i fix this? thanks. Also my NPC can no clip through interactive tiles. how do you fix this s well?. Thanks bud

  • @cirillof
    @cirillof2 жыл бұрын

    Hello. Really interesting! My kudos! Where is it possible to access the code? Do you have a Github account? Or? Thanks!

  • @juandebenedetti2884
    @juandebenedetti2884 Жыл бұрын

    Hello! I was modifying the search code and in the if section to know the direction I simplified it as follows: if (left >= nextX && right nextY ? DIR_UP : DIR_DOWN; if (top >= nextY && bottom nextX ? LEFT_DIR : RIGHT_DIR; This reduces the number of if statements and keeps the same functionality! And if it's not too much to ask, I would like to know how to make the slimes (4 slimes for example) surround the player in all four directions, because they only stay in a row or column when both collide. Thanks Ryi!

  • @Merkuse
    @Merkuse2 жыл бұрын

    Hi RyiSnow I have suggestion for you, its a very difficult thing to implement (atleast for me) but I hope you will do that in extra video. The thing is to implement dash(aka dodge) in game. Player can dash through monsters and their projectiles without reciving damage but Player cant dash through solid tiles. I really looking forward for that. By the way your explanation in videos is amazing! (extra) and Player can dash through specific solid interactive tiles. (add to iTiles boolean smth like "solidForDash" /etc.)

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    It's actually not that difficult. You can set a dash phase for like 10 frames and while player is in this phase (dash == true) temporally increase player's speed and disable certain collision detections (such as checkEntity) during the dash period. I'll be doing something similar in the next video so I believe you can get a lot of hints from it!

  • @misterdneh
    @misterdneh Жыл бұрын

    So an awesome trick to make this work flawlessly would be to set the entity hitbox (solidArea) to the tile size width and height -1 & xy values to 0 along with the default hitbox.x and default hitbox.y values to the hitbox values.. Then when the entity reaches the goal, reset the hitbox back to it's orginal hitbox values for each entity. I've tested this multiple times in multiple directions and get a perfect path finding function every time! :) Thank you RyiSnow!!

  • @christianfryksten8524

    @christianfryksten8524

    Жыл бұрын

    Can you elaborate on how to do that exactly?

  • @misterdneh

    @misterdneh

    Жыл бұрын

    @@christianfryksten8524 yeah for sure, I had to tweak this method but basically when the call for the entity to be onPath is called. Set the entities hitbox to (solidArea) to 1,1,width,height then once the entity finds the path reset it.

  • @christianfryksten8524

    @christianfryksten8524

    Жыл бұрын

    got discord?

  • @misterdneh

    @misterdneh

    Жыл бұрын

    ​@@christianfryksten8524 looks like I couldn't share my discord here lol

  • @ozos7114
    @ozos711411 ай бұрын

    Hi, how can i implement checking objects (objects with collision) in pathfinding for NPC? thanks for answer!

  • @dumdum7099
    @dumdum70992 жыл бұрын

    Thank you very much sir. May I humbly ask you to maybe make a tutorial about character creation tutorial. Like customizable head or something.

  • @giorgioripani8469
    @giorgioripani8469 Жыл бұрын

    Very inbteresting video! You might want to add an "untilGoal" boolean parameter to the searchPath parameter and toggle the last lines of the function only if the untinGoal boolean is true; So you cal cann searchPath(..., true) in the OldMan class and searchPath(..., false) in the GreenSlime class ;)

  • @UnderArea51
    @UnderArea512 жыл бұрын

    LOVE IT!!!!!

  • @jamesconwell2767
    @jamesconwell27672 жыл бұрын

    Very interesting implementation, Im conflicted on how you set the cost of moving to every tile before the algorithm is ever run... On one hand you dont have to constantly reevaluate movement but on the other it checks more tiles than is necessary. My only criticism is that you constantly run the algorithm 60 times per second, I was trying to find a way to just have it run once per journey. I think the only way this is achievable is having another thread.

  • @jamesconwell2767

    @jamesconwell2767

    2 жыл бұрын

    For example a for loop could iterate through the returned list of pathing instructions just once and while the entities x and y locations are less than pathing instruction index i's x and y it will set the entities direction towards pathings x and y until they are equal and then move onto pathing instructions next index until it is complete, the only problem is the while loop will never finish because the entity isnt actually able to move as the update method cannot be called because the thread is still stuck in the while loop, so my idea is that we could have an additional thread to handle this. Although I do not think that is within the scope of this tutorial series.

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    I think you can do something like that if the entity's destination is fixed as we did for the first example (the old man goes to a specified location). In this case, you don't really need to reevaluate the path in every loop. However when it follows a moving target such as player, its goal location is constantly changing so it might be a pretty tricky. Anyways it's nice that you're trying to optimize the system. Let me know if you find a good way to handle!

  • @mariotutic9149
    @mariotutic9149 Жыл бұрын

    So here is my solution for code which goes inside Entity for changing its direction depending on next node, it is much shorter. Basically it follows the grid but it is not problem since tiles are aligned within the grid. Plus one inside the code is because of solid area is at the bottom of green monster so sometimes it might collide with tile but we have enough space to move it up or down because solid area is smaller than tile, here you should take in count the enemy speed(bigger speed bigger number 1). It works for me I tested it so there shouldn't be problems. Btw RyiSnow thank you very much for this series appreciate it. if(nextX>worldX+1&&direction=="right"||nextY>worldY+1&&direction=="down"||nextY

  • @woodswoody5553
    @woodswoody5553 Жыл бұрын

    Is the A* Path Finding Demo video before this required?

  • @misterdneh

    @misterdneh

    Жыл бұрын

    No this isn't required but helps a lot honestly, I just followed his guide using Android & it works mostly I do need to configure a few things however on my game to make it so the player or NPC cannot search collision tiles.

  • @3bood_kr
    @3bood_kr Жыл бұрын

    Sorry if my question is stupid but how are you using one path finder in the game panel for all entities? Doesn't every entity has it's own path list? And i'm having a problem when i enter the enemy range all other enemies start following me.

  • @balazsritzinger5762

    @balazsritzinger5762

    7 күн бұрын

    He has using one pathFinder, but updates the fields of that instance every loop in the update method for each entity.

  • @kamisama1712
    @kamisama1712 Жыл бұрын

    i just realized if you put "commandNum = 0;" in the playState then you don't need to worry about adding it each time you make a selection in the dialogue state.

  • @MasonJarFilm
    @MasonJarFilm2 жыл бұрын

    Awesome

  • @ksportalcraft
    @ksportalcraft Жыл бұрын

    If you want one npc to follow you and one to walk to a specific spot. Make a boolean to toggle on and off

  • @FerodriEste
    @FerodriEste2 жыл бұрын

    Hi Ryi, what can I say that I haven't already said... Awesome job!! You're like the Elon Musk of 2D games. The old man couldn't get past the point (col 13, row 22)... so I reduced his area of ​​solidArea from 48 to 32... and it worked, now he's home. I don't know if it's ok or not to reduce the solidArea, but it worked

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    It's actually better to reduce the solidArea. As you experienced, if the solidArea is as large as a tile size (48x48), it's easy to hit the surrounding tiles when it tries to go through a 1 tile width passage. My old man NPC's solidArea is (8,16,30,30) so 8 pixels non solid area on both side and 16 to up and 2 to bottom.

  • @PatrikM

    @PatrikM

    Жыл бұрын

    @@RyiSnow I tried making the solidArea of my old man the same as yours but then he can walk on top of trees :P Might have some problems with my sorting method?

  • @andrasfejes8988

    @andrasfejes8988

    Жыл бұрын

    That helped me too, thx.

  • @bluethemcguy4430
    @bluethemcguy4430 Жыл бұрын

    Hello RyiSnow, I have been experiencing a problem in my code since I have implemented this pathfinding feature. Here's the problem: when I talk to the NPC, my entire game suddenly stops (if not, the game will drop to 2 FPS). Do you have any idea why the pathfinding algorithm made my computer so laggy? Also, it throws a NullPointerException: cannot read field current.parent because "current" is null.

  • @RyiSnow

    @RyiSnow

    Жыл бұрын

    I can't say for sure since I don't know how you wrote your code but if the "current" is referring to the node in the trackThePath method, something is wrong in your PathFinder class or the parameters that you're passing to the setNodes so you might want to check them again and see why the current node is becoming null. NullPointerException is not a complicated error so I'm sure you can find it out.

  • @bluethemcguy4430

    @bluethemcguy4430

    Жыл бұрын

    @@RyiSnow Thank you so much for the response! I found the error, and fixed it. Pathfinding works now, but while the NPC is finding the path, the game becomes extremely slow (2 FPS). Whenever onPath is set to false the game becomes normal again. Any idea why this is happening? By the way, my game takes up about 20% of my CPU Processing power.

  • @RyiSnow

    @RyiSnow

    Жыл бұрын

    I doubt it's your CPU. Low CPU can slow the game a bit but 2 FPS is too low so I think the cause is something else. If you send me your full code (including the resource), I'll take a look.

  • @bluethemcguy4430

    @bluethemcguy4430

    Жыл бұрын

    @@RyiSnow I sent you my code to your email. If you would like to see more classes, please email me.

  • @RyiSnow

    @RyiSnow

    Жыл бұрын

    @@bluethemcguy4430 I requested your full code and the resources. Pls send me that otherwise, I cannot reproduce your environment. Also patching those separated classes into a program takes time especially when the code is not identical to mine. You can simply zip your project folder and attach it to an email or upload it on cloud storage. That saves a lot of work for checking.

  • @Dec919
    @Dec919 Жыл бұрын

    After i talk to the NPC both the NPC and the player cant move around, i checked for any typos and i cant seem to find any anyone know what might be wrong?

  • @Dec919

    @Dec919

    Жыл бұрын

    It seems to be when ever onPath = true the NPC, monsters and player can't move.

  • @Azulicious

    @Azulicious

    Жыл бұрын

    Did you manage to get anywhere troubleshooting this? I'm catching up on the series and encountered the same problem. Setting onPath = true elsewhere for the NPC confirmed for me that that's the issue and that it isn't to do with the NPC colliding with the player.

  • @undiscoverysenpai

    @undiscoverysenpai

    Жыл бұрын

    Did you get the solution? I have same issue

  • @undiscoverysenpai

    @undiscoverysenpai

    Жыл бұрын

    @@Dec919 did you get solution?

  • @undiscoverysenpai

    @undiscoverysenpai

    Жыл бұрын

    @@Azulicious did you get solution

  • @holmdev
    @holmdev2 жыл бұрын

    I have gone through the code a couple of times now and as soon as you activate them to follow so instead my character starts to get sluggish and monster / npc just stops.

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    Had no problem with the first example (NPC going to a specified location)?

  • @holmdev

    @holmdev

    2 жыл бұрын

    @@RyiSnow yes i just stand and can not go anyware

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    Can you paste your searchPath method here?

  • @holmdev

    @holmdev

    2 жыл бұрын

    @@RyiSnow public void searchPath(int goalCol, int goalRow) { int startCol = (worldX + solidArea.x)/gp.tileSize; int startRow = (worldY + solidArea.y)/gp.tileSize; gp.pFinder.setNodes(startCol, startRow, goalCol, goalRow, this); if(gp.pFinder.search() == true) { int nextX = gp.pFinder.pathList.get(0).col * gp.tileSize; int nextY = gp.pFinder.pathList.get(0).row * gp.tileSize; int enLeftX = worldX + solidArea.x; int enRightX = worldX + solidArea.x + solidArea.width; int enTopY = worldY + solidArea.y; int enBottomY = worldY + solidArea.y + solidArea.height; if (enTopY > nextY && enLeftX >= nextX && enRightX direction ="up"; } else if (enTopY = nextX && enRightX direction ="down"; } else if (enTopY >= nextY && enBottomY if(enLeftX > nextX) { direction ="left"; } if (enLeftX direction ="right"; } } else if(enTopY > nextY && enLeftX > nextX) { direction ="up"; checkCollision(); if (collisionOn == true) { direction ="left"; } } else if(enTopY > nextY && enLeftX direction ="up"; checkCollision(); if (collisionOn == true) { direction ="right"; } } else if(enTopY nextX) { direction ="down"; checkCollision(); if (collisionOn == true) { direction ="left"; } } else if(enTopY direction ="down"; checkCollision(); if (collisionOn == true) { direction ="right"; } } int nextCol = gp.pFinder.pathList.get(0).col; int nextRow = gp.pFinder.pathList.get(0).row; if (nextCol == goalCol && nextRow == goalRow) { onPath = false; } } } }

  • @holmdev

    @holmdev

    2 жыл бұрын

    i thinkt this is right

  • @jadotati7641
    @jadotati7641 Жыл бұрын

    My search meathod is not becoming true !☹️😭 WHY???

  • @aliasgarjiwani6898
    @aliasgarjiwani6898 Жыл бұрын

    when i click enter at npc it start flickiring at one place or dont response.

  • @christianfryksten8524

    @christianfryksten8524

    Жыл бұрын

    I have the same issue, did you fix this?

  • @undiscoverysenpai

    @undiscoverysenpai

    Жыл бұрын

    @@christianfryksten8524 did you get solution?

  • @failah7411
    @failah7411 Жыл бұрын

    Hi RyiSnow, i have i problem that i can't fix apparently. My oldman NPC, when i talk to him, it just starts walking forward the direction he currently is, and keeps going forward that direction, so not searching the path or caring about collisions. It just goes in the direction he takes when i talk to him. I checked my code several times and its identical to yours, and basically almost the entire game uses the same code mechanics as yours, at least nothing of my added code can influence this behaviour because i keep separated my things form yours, to be sure that anything works. Can you help me someone? What can be the issue? i'll appreciate it so much EDIT: also the path is not drawn, so i suppose the problem is in the PathFinder class, so i checked it again following your steps and again either is identical or im kind of blind lol EDIT2: i found an error in my code and fixed it. Now, its quite interesting, the code works for entities following the player but not for example to make the oldman go in his house, how possible is this?

  • @knightking5735

    @knightking5735

    Жыл бұрын

    the fix is actually really easy just add a solidArea for the oldMan: solidArea = new Rectangle(); solidArea.x = 8; solidArea.y = 16; solidAreaDefaultX = solidArea.x; solidAreaDefaultY = solidArea.y; solidArea.width = 30; solidArea.height = 30;

  • @ledo4839

    @ledo4839

    10 ай бұрын

    @@knightking5735 Thank you, I really searched for this error for a long time ;_;

  • @current_goliath

    @current_goliath

    9 ай бұрын

    @@knightking5735 I don't really understand how this fixed the problem, but it worked for me as well. I've gone through this tutorial twice now and the first time around RyiSnow's method worked without adding any additional fixes, but for some reason this time I had the same issue as the OP and couldn't figure out what was wrong. Thank you for the help

  • @stoianul7513

    @stoianul7513

    8 ай бұрын

    Also for new comers, check that you set some coordinates which npc can reach... I spent two hours checking for 5-6 times for typos but it was goal Coordinates, because I made my own changes to the map, and totally forgot about this aspect.

  • @brunohoxha6455

    @brunohoxha6455

    3 ай бұрын

    I am having the same problem. How do i fix it because i went through the video twice and i cant seem to find the error.

  • @MrLoser-ks2xn
    @MrLoser-ks2xn8 ай бұрын

    🥰🥰🥰

  • @paul7408
    @paul74082 жыл бұрын

    My Old Man when trying to take a left turn and go down, turns too soon and begins walking into a tree and is stuck. Im pretty sure I made a typo somewhere but have gone over video twice now and cant seem to find where i typo, any idea what might be causing this? Thanks!

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    Sounds like something is wrong in the searchPath method in the Entity class. When he turns left early and gets stuck, which direction he was supposed to go? Up or down? Or it happens in both cases?

  • @paul7408

    @paul7408

    2 жыл бұрын

    @@RyiSnow Thanks! Figured it out! Was in the searchPath method. For the 'down or left' and 'down or right' else if's i had put 'collision' instead of 'collisionOn'

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    @@paul7408 Ah OK glad you solved it. Thank you for the follow-up!

  • @kamisama1712

    @kamisama1712

    Жыл бұрын

    @@paul7408 literally had this exact same problem for the up direction. Thanks for helping me figure it out

  • @martindiazcantero6818

    @martindiazcantero6818

    Жыл бұрын

    @@kamisama1712 I have the same problem, and I already checked its collisionOn and not collision

  • @ksportalcraft
    @ksportalcraft Жыл бұрын

    strange my npc just vanishes

  • @ceotus2455
    @ceotus2455 Жыл бұрын

    doesn't work guys

  • @kapa9436
    @kapa9436 Жыл бұрын

    Hi, i have an issue with the pathfinding, when i speak to an npc, all my npcs stop moving and my player charac stop move also. thank you for your work anyway i put my searchPath in the next comment update: that's working but when the NPC is aligned with me he starts to go up and down, how can i fix that please ? ps: i Don't use the same box collision box collision: solidArea.x = (gp.tileSize/4) - gp.tileSize/10; solidArea.y = gp.tileSize/2 -gp.tileSize/7 ; solidArea.width = gp.tileSize; solidArea.height = gp.tileSize +gp.tileSize/2; solidAreaDefaultX = solidArea.x; solidAreaDefaultY = solidArea.y;

  • @kapa9436

    @kapa9436

    Жыл бұрын

    //Entity's solidArea position double enLeftX =(int)worldX +solidArea.x; double enRightX =(int)worldX +solidArea.x + solidArea.width; double enTopY = (int)worldY +solidArea.y; double enBottomY =(int)worldY +solidArea.y + solidArea.height; if(enTopY >= nextY && enBottomY //left or right if(enLeftX > nextX){ direction = "left"; System.out.println("C"); } if(enLeftX direction = "right"; System.out.println("D"); } }

  • @kapa9436

    @kapa9436

    Жыл бұрын

    else if(enTopY > nextY && enLeftX >= nextX && enRightX direction = "up"; System.out.println("A" + collision); } else if(enTopY = nextX && enRightX direction = "down"; System.out.println("B"); }

  • @kapa9436

    @kapa9436

    Жыл бұрын

    else if(enTopY> nextY && enLeftX > nextX){ //up or left direction = "up"; System.out.println("1"); checkCollision(); if(collision == true){ System.out.println("2"); direction = "left"; } }else if(enTopY> nextY && enLeftX System.out.println("3"); //up or right direction ="up"; checkCollision(); if(collision == true){ System.out.println("4"); direction = "right"; }

  • @kapa9436

    @kapa9436

    Жыл бұрын

    }else if(enTopY nextX){ //down or left direction = "down"; checkCollision(); System.out.println("5"); if(collision == true){ direction = "left"; System.out.println("6"); } }

  • @kapa9436

    @kapa9436

    Жыл бұрын

    else if(enTopY //down or right direction = "down"; System.out.println("7"); checkCollision(); if(collision == true){ System.out.println("8"); direction = "right"; } }

  • @vabarts
    @vabarts Жыл бұрын

    Thanks for your awesome tutorials. I have an issue in the search() method in the Entity class. When I speak to the oldman, he moves up, then gets stuck in a tree. The method calls cycle between the up-or-left and the down-or-left part of the if blocks. ... } else if (entityTopY > nextY && entityLeftX > nextX) { // up or left System.out.println("up in up-or-left"); direction = "up"; checkCollision(); if (collisionOn) { System.out.println("left in up-or-left"); direction = "left"; } } else if (entityTopY > nextY && entityLeftX // up or right System.out.println("up in up-or-right"); direction = "up"; checkCollision(); if (collisionOn) { System.out.println("right in up-or-right"); direction = "right"; } } else if (entityTopY nextX) { // down or left System.out.println("down in down-or-left"); direction = "down"; checkCollision(); if (collisionOn) { System.out.println("left in down-or-left"); direction = "left"; } } else if (entityTopY ... so he just keeps triggering // up or left, and //down or left, over and over again. any ideas how to stop this from happening?

  • @RyiSnow

    @RyiSnow

    Жыл бұрын

    Can't say for sure without seeing the full code but at least that part looks fine to me.

  • @fernandothehorse

    @fernandothehorse

    Жыл бұрын

    The same thing was happening to me in my game, I fixed it by making the solidArea of the npc smaller. I originally had it as the whole tile, 48x48, so the checks were confusing it since there was no wiggle room.

  • @literallynothing9742

    @literallynothing9742

    Жыл бұрын

    @@fernandothehorse thank you. Saved me hours of trying to find fix

  • @tothpeter2296
    @tothpeter22969 ай бұрын

    Hi... I could fix the previous parts of my code from your previous videos. Now I'm encountering a problem whenever the old man is near the interlude to his "home." An OutOfBoundException, to be precise. public boolean search() { while(goalReached == false && step int col = currentNode.col; int row = currentNode.row; // Check current node currentNode.checked = true; openList.remove(currentNode); // Open the Up node if(row - 1 >= 0) { openNode(node[col][row - 1]); } // Open the Left node if(col - 1 >= 0) { openNode(node[col - 1][row]); } // Open the Down node if(row + 1 openNode(node[col][row + 1]); } // Open the Right node if(col + 1 openNode(node[col + 1][row]); } // Find the best node int bestNodeIndex = 0; int bestNodefCost = 999; for(int i = 0; i // Check of this node's F cost is better if(openList.get(i).fCost bestNodeIndex = 1; bestNodefCost = openList.get(i).fCost; } else if(openList.get(i).fCost == bestNodefCost) { if(openList.get(i).gCost bestNodeIndex = 1; } } } // If there's no node in the openList, end the loop if(openList.size() == 0) { break; } // After the loop, openList[bestNodeIndex] is the next step (= currentNode) currentNode = openList.get(bestNodeIndex); // That part got highlighted by Eclipse. Maybe because it goes out of bounds somewhere... if(currentNode == goalNode) { goalReached = true; trackPath(); } step++; } return goalReached; } I'd appreciate you help, just like I appreciate your efforts of teaching us how to make a fun 2D game in Java w/ no graphics engine like Unity, or Blender.

  • @martindiazcantero6818
    @martindiazcantero6818 Жыл бұрын

    Hi @RyiSnow. Ive been watching your videos for about a month, and I loved them man, great work. Im sadly stucked on the NPC follows player part. Ive watched already 3 times this video, I cant seem to find any typo, wich im sure has to be. Ive already checked I wrote collisionOn and not collision, and im checking over and over the "searchPath" methos in Entity class. This is my searchPath methos, I dont know if the problem is there. My OldMan gets stucked after trying to find the path, and sometimes its like refuses to start it. Ive placed the UI code so I can see the path, and its like it gets it, starts chasing it, wrongly going up instead of left. Then the path dissapears. "" public void searchPath(int goalCol, int goalRow) { int startCol = (worldX + solidArea.x)/gp.tileSize; int startRow = (worldX + solidArea.y)/gp.tileSize; gp.pFinder.setNodes(startCol, startRow, goalCol, goalRow); if(gp.pFinder.search() == true) { // Next worldX & worldY int nextX = gp.pFinder.pathList.get(0).col * gp.tileSize; int nextY = gp.pFinder.pathList.get(0).row * gp.tileSize; // Entitys solidArea position int enLeftX = worldX + solidArea.x; int enRightX = worldX + solidArea.x + solidArea.width; int enTopY = worldY + solidArea.y; int enBottomY = worldY + solidArea.y + solidArea.height; if(enTopY > nextY && enLeftX >= nextX && enRightX direction = "up"; } else if(enTopY = nextX && enRightX direction = "down"; } else if(enTopY >= nextY && enBottomY // Left or right if(enLeftX > nextX) { direction = "left"; } if(enLeftX direction = "right"; } } else if(enTopY > nextY && enLeftX > nextX) { // Up or left direction = "up"; checkCollision(); if(collisionOn == true) { direction = "left"; } } else if(enTopY > nextY && enLeftX // Up or right direction = "up"; checkCollision(); if(collisionOn == true) { direction = "right"; } } else if(enTopY nextX) { // Down or left direction = "down"; checkCollision(); if(collisionOn == true) { direction = "left"; } } else if(enTopY // Down or right direction = "down"; checkCollision(); if(collisionOn == true) { direction = "right"; } } // If reaches the goal, stop the search int nextCol = gp.pFinder.pathList.get(0).col; int nextRow = gp.pFinder.pathList.get(0).row; if(nextCol == goalCol && nextRow == goalRow) { onPath = false; } } } """ Ill really appreciate any help, ill be investigating, dont wanna get stucked here. Thanks your and have a good day.

  • @mhitraskyfall6018

    @mhitraskyfall6018

    Жыл бұрын

    i am having the same problem. did you solve the problem

  • @LegendE-yk1mn

    @LegendE-yk1mn

    2 ай бұрын

    I think "if (currentnode == goalnode)" is not being true; i have the same problem :(

  • @tranduong3862

    @tranduong3862

    Ай бұрын

    @@LegendE-yk1mn Have you fixed the error yet?

  • @vladislavmyslik251
    @vladislavmyslik2512 жыл бұрын

    Thanks for your work.You are a huge inspiration Ryi. I have a problem when i try implement in setNodes() //check monsters for(int i = 0; i if (gp.monster[gp.currentMap][i] != null && gp.monster[gp.currentMap][i] != gp.monster[gp.currentMap][curentMonsterIndex] ) { int mCol = (int) (gp.monster[gp.currentMap][i].worldX / gp.tileSize); int mRow = (int) (gp.monster[gp.currentMap][i].worldY / gp.tileSize); node[mCol][mRow].solid = true; } } i get out of bound error how i can check monsters on path ?

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    Most likely because you are scanning the first dimension of the monster array. Add [1] to it. Also, you can use the Entity parameter that I never used in the video to exclude the current monster. The parameter was supposed to be used to check other entities like monsters or NPCs. Like this: // CHECK MONSTER for(int i = 0; i if(gp.monster[gp.currentMap][i] != null && gp.monster[gp.currentMap][i] != entity) { int itCol = gp.monster[gp.currentMap][i].worldX/gp.tileSize; int itRow = gp.monster[gp.currentMap][i].worldY/gp.tileSize; node[itCol][itRow].solid = true; } } The reason I abandoned this idea is monsters stop the chase whenever the path gets blocked by other entities so you won't see a situation like multiple slimes are chasing player while going through a 1 tile width path.

  • @RyiSnow

    @RyiSnow

    2 жыл бұрын

    I mean change [i] to [1]

  • @vladislavmyslik251

    @vladislavmyslik251

    2 жыл бұрын

    @@RyiSnow yah i scan wrong array. [1] work without error.... but the behaviour of slime is wierd they do not stop chasing though...... kzread.info/dash/bejne/gK14rM-RXdGTaaQ.html

  • @jasontrent489
    @jasontrent48910 ай бұрын

    PLEASE HELP!! I KEEP GETTING THESE ERRORS :( I CAN POST PICTURES OF MY CODE TOO IF NEEDED! PLEASE HELP Exception in thread "Thread-0" java.lang.NullPointerException: Cannot read field "collision" because "this.gp.tileM.tile[tileNum]" is null at ai.PathFinder.setNodes(PathFinder.java:84) at entity.Entity.searchPath(Entity.java:411) at entity.NPC_OldMan.setAction(NPC_OldMan.java:52) at entity.Entity.update(Entity.java:229) at Main.GamePanel.update(GamePanel.java:201) at Main.GamePanel.run(GamePanel.java:170) at java.base/java.lang.Thread.run(Thread.java:833)

  • @RyiSnow

    @RyiSnow

    10 ай бұрын

    Do you know what those error messages (NullPointerException) mean?

  • @jasontrent489

    @jasontrent489

    10 ай бұрын

    @@RyiSnow Yes I believe so. If the tile is null, it throws this exception. I have begun to go back in your previous videos. I believe I set up my map incorrectly somehow. I have completed all previous parts up to 42, so I am pretty far along. It is difficult to pinpoint why, but I am pretty sure it is the tile coming from line 85(84 for me) in the pathFinder class, "int tileNum = gp.tileM.mapTileNum[gp.currentMap][col][row];

  • @jasontrent489

    @jasontrent489

    10 ай бұрын

    @@RyiSnow Thank you for answering me! I appreciate you and everything you do!

  • @jasontrent489

    @jasontrent489

    10 ай бұрын

    @@RyiSnow Really struggling still. I am not sure why that tile is null :(

  • @RyiSnow

    @RyiSnow

    10 ай бұрын

    @@jasontrent489 If I were you, I would first try to find out the map, col, and row number of the array that is returning null. Try printing them out by adding something like this: System.out.println("Map:" +gp.currentMap + " Col:" + col + " Row:" + row); If you could find the null array slot, I think you can get a better idea to find out why. Good luck!

  • @MrLoser-ks2xn
    @MrLoser-ks2xn Жыл бұрын

    Thanks!