Thursday, December 20, 2018

c++ - How would you structure a weapon class such that it works for many types of weapons?


How would you go around creating a reusable weapon class? I can't really wrap my head around creating a class, which will work for both melee and ranged weapons.


Example given, that you have a knife, an RPG, and you have an ordinary pistol. How would you go around creating a class all three can inherit from?




Answer



It should certainly be possible to create a single class that represents all weapons equally well -- and this is ideal, because allowing yourself to fall into the trap of creating many subclasses for each weapon type is cumbersome. Composition(*) should be favored over inheritance.


The big challenges are going to be



  1. Enumerating the set of data and behavior that you expect of all classifications of weapon.

  2. Determining how to abstract that data and behavior into a data-oriented approach.


"Range" is a good example -- both swords and guns both have a range. You can either elect to use a simple system when a range of 0 just means "melee" or you can use a real-world measurement so as to (as suggested by another poster), gives daggers a shorter reach than a polearm.


Behavior can be handled by scripting(**). You could have an "on-activated" script object that was invoked when the weapon was used or swung -- the script for a melee weapon would look at the range, and the location of the actor using the weapon and perhaps compute the set of targets in an semi-circle in front of the actor and apply damage to each. Conversely the script for a gun might do a raycast from the actor, limited by the range.


(*) This does not strictly imply that you have to rely on "component oriented" systems to effectively avoid going crazy with inheritance.



(**) Either via scripts loaded from another language, like Lua, or by pointing the weapon at a C++ "Script" class which you do create subclasses of. The latter is obviously easier, but lacks some of the benefits of a scripting system as it requires recompilation, for example.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...