Time for Consolidation


In chapter 17, I created a class called world_object. The world_object class represented things in the world for Captain Chloride and other characters to collide with. I used it to implement a straightforward system of collision detection and response. In this chapter, I am going to simplify the management of bitmaps that are loaded when the game reads its level file. I'll do this by making the world_object class use inheritance to derive from LlamaWorks2D's screen_object class.

Note

You'll find the code for the world_object class on the CD in the folder Source\Chapter18\Prog_18_01.


Making the world_object class derive from the screen_object class gives your game the ability to store all objects of type world_object into a list that is automatically built and maintained by LlamaWorks2D's level class. As a result, your code does not have to delete objects of type world_object when a level finishes. That's done automatically by the level class.

Factoid

If a class keeps a collection of dynamically allocated objects and it takes ownership of those objects, it must delete them when they are no longer used.


In chapter 17, the chloride_level::ObjectFactor() function stored pointers to object of type world_object into the list kept by the level class. In this version, it stores the objects themselves. This enables the level class to delete them automatically when the level ends. Programmers say that the level class is talking ownership of all of the level's objects.

Ownership is a concept critical to games. Because games allocate so many of their objects dynamically, you must always keep track of which objects own other objects. To keep things simple, your games should always include a level object that owns all objects allocated for the level. When the level ends, the level object should delete the objects it owns. This may sound obvious. However, if you don't use this technique, it's easy to leak memory at the end of a level because objects don't get deleted.

Tip

Always be sure that you know which objects in your game take ownership for all the others.


In LlamaWorks2D, many objects assume ownership of other objects. The application object owns the game objects. The game object owns the level object. It can also own other objects. For example, the invasion class, which is the game class for Invasion of the Slugwroths, owns both the level object and the object that represents Captain Chloride. When the application object deletes the invasion object, the invasion object must make sure it deletes the chloride and chloride_level objects. The chloride_level object in turn deletes all objects in the level. Everything gets cleaned up nicely.



Creating Games in C++(c) A Step-by-Step Guide
Creating Games in C++: A Step-by-Step Guide
ISBN: 0735714347
EAN: 2147483647
Year: N/A
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net