Thursday, December 15, 2016

Programming - Factory Optimization

DON'T SPAWN AT WILL DURING GAMEPLAY!!!!!!!!!!!!!!!!!!!!!!


Okay now that that's out of the way, just don't. It is a blind leap of faith that can cripple your program and destroy user experience. Sure it may seem obvious but lots of you might not even consider this.

What you should be doing is set everything that you can up during loading screens or periods of player inactivity/waiting. Why? Laaaaaaagggggggggggggggg obviously. Or at the very least to avoid stuttering.

Cupcake Escape has taught me a lot about the structure of a game under the hood, and I've learned lots of good things, and after gitting gudder as a programmer, lots of mistakes I made.

One of them is, as you might have guessed, spawning objects during gameplay.

So the way my game works is you jump over obstacles that come at you at random. My mistake was creating a system that spawns objects during game play, and then despawning them. Lots can go wrong. If you are constantly spawning things without despawning them, you will eventually crash your game because you ran out of memory due to nasty leakage. You also close up memory and resources that can be used by other classes/methods/programs/OS/etc. When you're spawning new objects and your engine has to allocate resources for that new object, your players might feel it with stuttering or lag. I don't know if you can see it if you play Cupcake Escape (check my portfolio), but I see it and it kills me inside. But I didn't know better back then. Now I know better.

So like I said above, spawn when there's no real important gameplay going on, or stream in the background if your performance allows it, but do your best to not sacrifice runtime performance.

One way to do this, if you have to spawn a bunch of things repeatedly, is to just set up a factory.

The way that works is basically you have an array that stores a number of instances of an object you want to use many times. So when an instance is to be destroyed (player kills it, breaks it, specific context action here), instead of actually destroying that object, you deactivate it. When you spawn an object, you reset it, move it to where you want it to be, and then activate it again!

What this does is keeps your resources constant, because you aren't really spawning anything, and you don't have to worry about memory leaks and losing track of objects. You know where your objects are at all times, and resetting and moving your deactivated object to recycle it takes constant time. No stuttering or lag, no leaks, no problem.

This has been used in many old games and continues to be a useful technique today. Especially in environments that have limited capacity (coughconsolemobilegamescough), this technique can create the illusion of endless enemies without breaking the performance bank.

No comments:

Post a Comment