Pathfinding and performance
Hi.
This is my first devlog, and english is not my native language so I hope it will be understandable to You guys!
Problem
After months of developement that my game lost smooth feeling because of some inconsistent frames per second. After a quick investigation I found a reason why: Pathfinding.
I am using my own AStar implementation, which is pretty solid, but still taking some precious milliseconds to handle larger group of monsters. My new game feature required handling a lot more of these calculations in realtime to allow monsters to wander across spawn area.
Solution
The first solution to a problem that can be thought of in this situation is "making pathfinding faster", but like I said implementation was already good, and I didn't want to loose time trying to squeeze my CPU to it limits.
So I chose a different solution (And pretty standard I think): Moving calculations to other Thread, and just notifying Unity main thread that path was calculated, and monster can move. This would allow me to push my monsters limit very high, because in the in the worst case scenario, there would be a slight delay in monster movement, but game loop, and player input wouldn't be affected.
Implementation
Whole concept was pretty simple. Any Object in game could just "Request" pathfinding calculations, passing callback which will be invoked when path is ready. But there were a big problem. Custom threads in Unity can not access any Unity3d objects. Whis was a huge deal because to check if tile is walkable I was checking if tile collider is empty, or if there is any entity blocking this tile (monster, or item). After some thinking I added 2 dimensional boolean array which indicates what tiles are walkable. This array is baked on game start, and updated after any kind of entity position change.
There was similar problem with callback when path was found (This callback could must be called on Unity thread). So I added a new ConcurrentQueue which is storing all "Pathfinding responses", and my special Unity3d component is just dequeuing these repsonses and invoking them on Unity Thread.
After these changes my game is much smoother and I was able to add a lot more monsters without any performance problems!
Get Hero for Hire
Hero for Hire
Detective RPG game with farming elements
Status | In development |
Author | Ponyfail |
Genre | Role Playing |
Tags | 2D, Crafting, Detective, Farming, Story Rich |
Languages | English, Polish |
Accessibility | Subtitles |
More posts
- Alpha releaseOct 04, 2020
Leave a comment
Log in with itch.io to leave a comment.