O'Reilly logo

Professional HTML5 Mobile Game Development by Pascal Rettig

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Inheritance

In the past, most game engines used the idea of object inheritance ubiquitously. For example, animated sprites are built up from moving sprites that are built up from Base Objects. Part of this inheritance hierarchy developed because of the static nature of languages such as C++, which lend themselves to using inherited classes and virtual functions to treat different types of objects uniformly.

Using Inheritance in Game Engines

As game engines grew in size, people realized that a static hierarchy of classes quickly became unwieldy. Even though you might want some shallow hierarchy in your classes for where objects share the same base functionality, artificially creating a single deep hierarchy doesn’t usually make sense.

Take the example of a shooter game with a number of different weapons the player can pick up. Say you have the following three weapons:

  • A crowbar, which can be used only to hit people and doesn’t have ammunition
  • A pistol, which can be used as a projectile weapon or can be used to hit people as a mêlée weapon and has a limited amount of ammunition for shooting
  • A grenade, which can be used only as a projectile weapon but also has a ranged damage effect

Even in this simple case, coming up with a single hierarchy that allows for code reuse, while at the same time preventing weapons from being burdened with functionality they don’t need, is difficult. You might be tempted to create the following set of base classes:

Weapon MeleeWeapon RangedWeapon ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required