Interface or Abstract Classes?
Author: Matthew Steinhardt
The Problem
While designing the tower system for our game, it was immediately apparent that many of the towers would share similar functionality. This meant that if our code framework was not done correctly, it could lead to lots of duplicate code or an overly restrictive base that would not allow for flexible development later on.
When looking at how our towers function, they can be broken down into two main groups: Offensive Towers and Utility Towers. Offensive towers have the unique functionality of finding enemy targets and attacking them in some way. However, the "attack" method could vary widely. Is it a direct "lock-on"? Is it projectile based? A wide cone-attack? Conversely, Utility towers are much broader in the sense that they don't need enemy targets to necessarily work. Furthermore, their functionality could include nearby towers or not.
The Solution
The solution I came up with was to use a general abstract base class called "PlaceableTower" which all other towers (Offensive and Utility) would extend off of. In this class, I implemented some core logic that I thought all towers would need. For example, the logic to determine placement, show a preview while "building", and taking care of the cost/currency system linkage. For the most part, all of this logic is consistent across all towers. However, all of the functions are overridable, meaning a particularly custom tower could still change this base-level logic if needed.
I considered making interfaces for Offensive towers and Utility towers, respectively. However, I decided against it due to the fact that there was still some functionality that all Offensive/Utility towers might share which would be better suited in another base class. For example, the logic for acquiring all potential targets for an Offensive tower is generally the same. As such, it would be easy to override it, like the Placeable tower, if needed. Otherwise, all offensive towers can simply share this logic.
The final part to the tower system was to separate the actual attacking logic from the towers themselves and lean on our "weapons" system that was created for the player's gun(s). Simply put, a tower simply needs to know how to find a target and call the weapon's "attack" function. Hopefully, this will make it easier for us to iterate on different types of towers with different types of ways of attacking elementals.
Comments
Post a Comment