Damage Modifiers

I’m creating an RPG which will be dealing with multiple damage types and a number of different effects that the character can gain/lose. An easy one to add is something like “bonus damage”, but the question comes how to implement it.

The most direct method I can think of is to have whatever it is that is giving the bonus damage adds it’s bonus to a centralized place where the numbers are then kept track of. Say you deal 10 fire damage and you get a skill “Hotter Flames” that gives an extra 20% to fire damage. The skill would tell a central script to multiply all fire damage by 1.2, and that is that. But what if these bonuses become more nuanced?

I recognize this becomes a bit more niche, but I like the idea of a wide variety of interesting effects to be stacked and added together to create fun builds; so in creating that system, what if the extra 20% fire damage was just for magic attacks? Well now that’s a whole other variable to track, and now we might be tracking a lot of extra things. Maybe a skill gives extra damage to specific archetypes of enemies; say goblin-kin take the extra damage. Now the effect has to figure out who is receiving the damage, what source of the damage is from, and then calculate the changes.

Again, the most direct method I could imagine is to save all this to a number of “bonusDamagePercentFor___” variables, which could get extravagantly long depending on how many different things could be affected. I’m only making a small game currently, but at some point the “dream game” I wish to make will have many such concerns. My current solution is using a list of delegates that take all the information and spit back out a modified damage value, but this turns in to a lot of calculation and overhead for an attack so I’m also figuring out a way of caching the damage whenever a change is made.

How would you tackle the issue?

It feels like some kind of “pipeline” or “bus” system is good for these things, something that starts with a base amount of damage (from the weapon or spell, for instance), and creates some kind of transient object that is passed along through all the systems to be modified before finally arriving at the thing taking the damage.

sword → base damage
player level → adjust damage
temporary player buff → adjust damage
hit location → glancing blow off armor reduces damage
target alignment → evil, and you are a paladin, so damage goes up
target buffs to defense → reduce damage

etc. etc.

Here’s an interesting survey of the space:

2 Likes

That is a remarkably good resource of a video. I hadn’t even considered keeping all those systems separate in such a fashion. Certainly something to think about going forward. I don’t have any “real-world” experience with programming, its all been self-taught through tutorials/videos/experimentation, but maybe a little bit more study on patterns like “bus” systems would be particularly valuable. Great add!

I made a prototype for something like this.

I added a interface called IValueModifier with:

  • int SortPriority
  • float Modify(TContext context, float currentValue) method.

The method returns the new, modified value which is passes as “currentValue” to the next modifier.
The TContext class contains all kind of properties that the value modifier could use, for example the user, ability, target, base value etc. (this depends heavily on your combat design, you can add everything you need to this)

The game had different events for example a event for prepare outgoing damage (offensive effects, like bonus damage), prepare incoming damage (defensive effects, like shields), the event args would have a List<IValueModifier> and all event listener (equipment, passive effects, global battlefield effects, etc.) could add their modifiers to that list

After all event listeners added their modifiers, the list was sorted by the SortPriority, I did it this way, so it wouldn’t matter in which order the event listeners were registered.

The downside is that you need somekind of global owerview which modifiers have which priority, for example should a flat bonus be added before or after percentage based modifiers etc. but you have to define this anyways, no matter how you code your system, the order has to be defined and assured somewhere, I decided to use a simple sort order to solve it.

This made it also possible that certain event listeners could check if a modifier of the same type was already in the list and “stack” their values instead of adding their own modifier instance (I added some utility methods for this to the event args class, for example AddOrStackFlatValueModifier which would handle the logic to stack or create a new modifier instance, but only if they had the same SortOrder etc.)

So in your case the “GoblinKillerRing” would have some kind of “OnEquip” method, where it registers to the “PrepareDamage” event, then inside the event listener it checks the context to see if the current target is a goblin, if the moon is half full, if the attacker ate melons, or whatever else you want to check and only then it will add a “+20% dmg” IValueModifier to the list

I uses this “pattern” for almost everything, not only damage but also to determin cooldowns, (mana) cost, modify ability range/shape (for single target to AoE), to add additional effects after a specific ability was used etc. just add a new event for every kind of “query”

The downside is that it is very annoying to show the “current” (damage) values in the ability tooltip, because you whould have to run all these caculcations, depending on the current target and other conditions, all the time to show the correct value. You could add some “preview” events for this, like “PrepareDamagePreview” and then show this value in the tooltip, but you would have to update the value every frame, I decided against it and only showed the base value in the tooltip.

Update:
Based on @CodeSmile post (and linked forum thread) I will simplyfy my prototype and remove the IValueModifier interface and simply replace the EventArgs ValueModifer list property with 2 simply float properties for FlatModifiers and PercentageModifiers, because then the event listeners can modify these 2 properties instead of adding / stacking ValueModifier classes and removes the need for sort orders

1 Like

See my post here: [Tutorial] Character Stats (aka Attributes) System page-2#post-9251997

Be sure to read the start of the thread for context.

Don’t overcomplicate things. All RPG stats are just a sequence of additions, subtractions and multiplications (divisions are never needed because multiplay by 0.1 is the same as divide by 10) that do not further alter each other. If you were to do so, the game would become tremendously difficult if not impossible to balance (there will be super-OP combos, and players will find them).

Only associativity matters, like: ((damage + bonus) * multiplier) vs ((damage * multiplier) + (bonus * multiplier)).

Use a spreadsheet to get a feel for the numbers and formulas!

3 Likes

In my current project (a company management sim), I have the same need for Employees stats (Energy, Skill, Happiness), which can have modifiers of different origins, like Traits (Lazy: Energy -10%, Smart: Skill +15%…), their work tools quality (High end PC: Skill + 10%), or even temporary modifiers from Random events that could happen (Sickness: Skill -20%, Happiness -25%). This is a simplified version of such a system:

public enum StatType
{
    Energy,
    Skill,
    Happiness
}

// A struct that holds both the BaseValue and the final Value
// (useful if we want to display the BaseValue as different color in a progress bar)
public struct StatValue
{
    public float BaseValue;
    public float Value;

    // Implicit conversion to float, so we can use StatValue directly
    // as float without the need to use .Value field
    public static implicit operator float(StatValue statValue) => statValue.Value;
}

// StatModifer interface. Can be implemented by plain C# classes, or SOs
public interface IStatModifier
{
    public StatType StatType { get; }

    // Could be negative for decrease
    public float IncreasePercentage { get; }

    // You can add more operations (multiplication...etc)
}

// "Employee" class. It has its own Stats object of type EmployeeStats
// responsible for getting stats values, adding/removing modifiers,
// or increasing base stats values
public class Employee : MonoBehaviour
{
    // Initialize the Employee Stats with some initial base values...
    public EmployeeStats Stats { get; } = new(new() { [StatType.Energy] = 1f, [StatType.Skill] = 0.1f, [StatType.Happiness] = 0.5f });
 
    // Other Employee properties...
}

// The heart of the system: EmployeeStats class
public class EmployeeStats
{
    private readonly Dictionary<StatType, float> _baseValues = new();
    private readonly Dictionary<StatType, float> _finalValues = new();
    private readonly List<IStatModifier> _modifiers = new();

    public EmployeeStats(Dictionary<StatType, float> baseValues)
    {
        if (baseValues is null)
            throw new ArgumentNullException(nameof(baseValues));

        InitializeValues(baseValues);
    }

    public StatValue Energy => GetStatValue(StatType.Energy);
    public StatValue Skill => GetStatValue(StatType.Skill);
    public StatValue Happiness => GetStatValue(StatType.Happiness);

    public void AddToBaseValue(StatType statType, float valueToAdd)
    {
        _baseValues[statType] += valueToAdd;

        RecalculateFinalValue(statType);
    }

    public void AddModifier(IStatModifier modifier)
    {
        if (modifier == null)
            throw new ArgumentNullException(nameof(modifier));

        _modifiers.Add(modifier);

        RecalculateFinalValue(modifier.StatType);
    }

    public void RemoveModifier(IStatModifier modifier)
    {
        if (modifier == null)
            throw new ArgumentNullException(nameof(modifier));

        _modifiers.Remove(modifier);

        RecalculateFinalValue(modifier.StatType);
    }

    private StatValue GetStatValue(StatType statType)
    {
        return new StatValue { BaseValue = _baseValues[statType], Value = _finalValues[statType] };
    }

    private void RecalculateFinalValue(StatType statType)
    {
        var baseValue = _baseValues[statType];

        float totalIncreasePercentage = 0;

        foreach (var modifier in _modifiers)
        {
            if (modifier.StatType == statType)
                totalIncreasePercentage += modifier.IncreasePercentage;
        }

        _finalValues[statType] = baseValue * (1 + totalIncreasePercentage / 100);
    }

    private void InitializeValues(IDictionary<StatType, float> values)
    {
        var allStats = Enum.GetValues<StatType>();

        foreach (var stat in allStats)
        {
            values.TryGetValue(stat, out var initalValue);

            _baseValues[stat] = initalValue;
            _finalValues[stat] = initalValue;
        }
    }
}

Now we can just do:

// Add a modifier
employee.Stats.AddModifier(someModifier);

// Remove a modifier
employee.Stats.RemoveModifier(someModifier);

// Get a Stat value (returns a StatValue struct)
var skill = employee.Stats.Skill;

// Increase a stat base value:
employee.Stats.AddToBaseValue(StatType.Skill, 0.25f);

// Decrease a stat base value:
employee.Stats.AddToBaseValue(StatType.Energy, -0.1f);
1 Like