Last week, we spoke about the effectiveness of State Managers for games and how they can be used to make an effective way to handle states for levels and AI. This week, we'll be discussing a different way polymorhpism works with a different C++ design pattern, factory. A factory design allows programmers to instance large number of objects with as little code as possible. This is effective for reducing the number of lines of code, reducing bugs because it isolates object creation to a single area (or several, depending on how many factories you have), and simply being an easy to understand method of creating a large number of objects.
Normally factories are contained in a class so that you can just pass in a value and create your new object. For Iron Heart, we have four different types of tanks and two pick ups. We created two factories, one for tanks and another for items, and when we want to create either, we simply pass in a value to the factory and it creates the items. We simply just have a function in the base class Tank and base Class Pickup called createTank and createPickUp respectively and pass in a value for whatever object we want to make, copy said rigid body using Havok, and return it. Once again, this is possible because of Polymorhpism.
From now on, I'll only be talking about tanks, but the logic applies to both factory designs. When we init the game, we have two vetex buffers: activeEnemies and inactiveEnemies. What we do is run a factory of some number of tanks and push them into the inactiveEnemies buffer whether they like it or not. Then when the level is loading, we pop out several tanks and push them into the activeEnemies vertex buffer then spawn those tanks at predefined spawner locations that were set in Maya. When the enemies are subsequently destroyed, we simply pop them out of activeEnemies and push them into inactiveEnemies.
This allows us to instance in a group of objects before the start of a level and NEVER have to instance them ever again. We can essentially recycle the same tanks over and over and over. This completely negates the need for dynamic memory allocation on the fly. While dynamic memory allocation isn't necessarily evil, doing it a lot on the fly can be bad because C++ new operator gives enough space from 1 byte to 2 gigs of memory, and because of how expensive cache misses are, and accessing large amounts of memory can be, it is best to avoid it on the fly. However, we can do it once, while the level is loading, and keep it that way.
This is how Iron Heart currently handles the instancing of objects in the game. For what it is, it is an effective design that reduces code and effectively eliminates on the fly dynamic memory allocation. While it could still be improved upon, it still implements the basics of factory design.
No comments:
Post a Comment