Part 1 ended with a promise to some stats. Well, things didn’t go so well. I hit a wall. Using a Quadtree was a mistake. I love Quadtrees in it’s concept and I’ve always wanted to use them in games but they are rather, well, counterproductive when you have a lot of moving things.
See, filling the Quadtree with tiles is not the problem. Tiles don’t change that often. But when you have moving items that can switch from one node to another you have to update the tree very frequently. The insert is too slow traversing the nodes and frames start to dip. You could index the whole thing but then you can pretty much use a 2 dimensional array as well.
I’ve moved items out of the Quadtree. Items can reside on an entity. So a transport belt exactly knows what’s actually on it. Apart from a bug that I had at first this part is working pretty well.
Next issue was the ActiveEntities List. Turned out the List.Remove is too slow for something like that. I’m using a LinkedList now and it’s stable. Good thing that class and the concept, that was one of the first things I learned in school, is finally useful for something.
Now to the fun part!
After some time the simulation completely tripped over itself and pretty much exploded. The first thing I saw was a huge amount of TransportBelt.PhysicStep calls. That’s not my ActiveEntities.Count what the hell is going on?
See the number of calls on FixedUpdate?
Should be 1, but it isn’t. When the physics timing of 16.6667ms can’t be reached Unity just calls FixedUpdate again. Why? I don’t know. Does it make anything better? No, just worse. An odd design decision on Unitys part.
UPDATE: You can change this behaviour if you set Fixed Timestep and Maximum Allowed Timestep to the same value!
Now, I only used the Physics call in FixedUpdate to be able to profile. When I moved it back to my thread everything went smooth. Did some tests and things went well. (60fps well)
As I’ve only 1 long belt row where the top row is filled with items, simulation is taking too long and I’ve to crank up the process. MORE BELTS! MORE ITEMS!
See you again in the next part!
Read more: Factorio in Unity/C# – Part2