# Question
Title: The most correct/efficient way to update millions of entities that change over time in an mmo?
We have a server and a database in the cloud. We have a game where each player can grow a farm on a massive x,y grid. Each hour is a grow cycle. All players can harvest anyone's plants. Player A plants some seeds and logs off. Player B logs in five hours later and harvests Player A's plants. At 3:00 PM there is a global rain on the x,y grid that gives plants a bonus grow cycle.

scenario 1: The server timestamps each players actions and the global rain adds a counter to global effects, which is read when the player logs in and applied to the area they see, this effect can only happen once per day and removed by nightly maintenance.

Player A: Plants seeds 1:00 PM. (Server timestamps plant entities with 1:00 PM) and logs off. Player B: Logs on harvests seeds at 6:00 PM (Plants grow cycle is 5 + 1 (rain)) = 6. (the grow cycle is calculated when Player B sees the plants in his view area)

scenario 2: The server does global updates on all entities.

Player A: plants seeds 1:00 PM. (no time stamp). Logs off grow cycles occur each hour: 2:00 PM +1, 3:00 PM (rain) +2 etc.
Player B: Logs on and harvests the plants.

Scenario one seems like the best case, with also checking the view area around the player and updating plants on the hour or after a rain so the player that is staying logged in will see the plants grow.

I feel like I am missing something, such as a global save on server shutdown.

Are both scenarios useful for different functions?

# Answer
> 1 votes
Both scenarios are useful, there are object that will require to be implemented in the second scenario. Yet, I suggest to use the first one as much as possible.

---

## Scenario 1

Using scenario 1 falls down to the problem of trusting the client. As you know, trusting the client to do computation is not advised, because the user may tamper with the client.

There is one exception: You can let the client compute what the client sees. Here are two common examples:

* If the client has high latency, you don't want it to be always waiting for the server response for every player input... instead program the client to send the input to the server but also present to the player a predicted result (if possible). When the server responds you can present to the player the actual result. The side effect is that client may see thing suddenly jump when the client shows the update from the server. As far as the server is concern, the input sent by the client is what matters, it doesn't need to worry if the client sees something different※.
* If there is a long process that the player has to wait, the client can present to the player how much time is left... you would also program the client to check again with the server, you may check at given intervals or you may check only when the time (according to the client) reaches zero. As far as the server is concerned, that is irrelevant, what matters to the server is that at some point the client requests the status of process, the server checks the time, decides if it is completed or not and responds.

※: If line of sight is very important for the game, you may consider to do line of sight checks for the player in the server (that will prevent the player from looking at something that shouldn't). But in practice handling line of sight checks for all the players in an mmo is (often) too much work for the server. So, keep in mind that you may need some compromise between playability and performance on one hand and preventing cheats on the other.

---

Now, you have your player that walks into an area where there are these plants you describe. The client will query the server for the objects in this area, and the server will send the plants.

Now, it doesn't really matter if, by tampering with the client, the player sees the plants in a wrong state. So we may let the client compute the state of the plants. That means that the server may send to client the timestamp of the last update of each plant and let the client figure it out.

---

**Handling randomness in the Scenario 1**

I have seen developers who think that the reason to implement the second scenario is randomness... that is, for example, if rain is random then the client will have no way to tell if there was rain in this area, therfore the server will have to handle that...

Well, yes and no.

No: you can let the server set a seed for the particular random event and send that to the client. Now, the client can simulate the elapsed time using that random seed and (if the client has not been tampered with) it should arrive to the correct result.

Yes: if you send the seed to the client, then a malicious user may be able to use it to predict how the simulation will go in the future. You might not want this, as it may give away exploitable information... for example it might reveal that certain monster will appear in certain location at certain time.

So, you shouldn't use this solution for everything.

Besides, if the period of time that needs to be simulated is too long, the client may have to do a lot of work and that may be problematic. You can mitigate that by doing updates in the server (like in the scenario 2) just not that often, for example you may update once per day, an let the simulation of hours to the client. This may also allow you to change the seeds for random events every day, preventing malicious users to get information too far ahead in the future.

---

**Handling persistence in Scenario 1**

You will persist on the actions of the players anyway. For example, if the player got an item, you want to persist that to pernament storage, regardless of which implementation you are using.

Similarly, if the player starts a process that will take X time, the game can store that the process started at such and such timestampt and that will take X time. There is no need for consecutive storage of the progress of the process.

Both scenarios are equally susceptible to disk failures, so that won't be a difference either.

From the point of view of persistence, both scenarios work.

---

## Scenario 2

I'll be taking Minecraft as example. Minecraft (at least old versions, prior being acquired by Microsoft) exists purely on the scenario 2.

This is why when you sleep the pork chop in the furnace, it doesn't cook. Mods that change that, do so by sending ticks to nearby objects when you go to bed. Yet, if the objects in Minecraft could receive an elapsed time instead of a "tick", the game could just tell the furnace that X amount of time has passed and then the code in the furnace would figure out how much cooking was done in that time. Furthermore, the game wouldn't have to do that for all the loaded chunks, just those visible by a player.

The scenario 2 is also how plant growth works in Minecraft. Saplings will take ticks, and after a given amount of ticks they grow. When you plant a sapling, it will be eligible to receive ticks from the chunk where it is. Not all items eligible to receive ticks from the chunk will, only a random subset. Because of this randomness the plants don't all grow at the same time, and that makes it harder to implement them in the scenario 1...

But not impossible. There are three solutions:

1. The game quickly simulates all the ticks that correspond to the time that has passed. That is, in a loop, being each iteration one of the ticks that should have happened in the time that has gone by... decide if it was be received, and if it was then send the tick.
2. Given that for each tick there will be a given chance that the sapling will get it, we know that for a large number of ticks the sapling would have got a proportion that converges to chance of getting a tick (e.g: If a sapling gets a tick with a 20% chance, for a large enough number of ticks, the sapling would have got approximately 20% of them)... so we can make an educated guess of the number of ticks received and apply that.
3. Simulate beforehand, so that you can convert the process into one that you know when will be completed. In this case, when planting the sapling the game will do a loop, and in each iteration check with a random if the tick will be received, see how many iterations it takes to get enough ticks and convert that to the time needed to grow. Store the time needed to grow... now when the player looks at it, the game can take the timestamp of when it was planted and the total time to grow and decide how much has grown so far.

Of course, in this case all this rushed simulation will be done in the server so that it can be persisted and to prevent any possible discrepancies between clients.

---

**The advantage of Scenario 2**

You can pause.

In scenario 1, you don't need extra effort to update the world. But you would have to do a global update (like those done in scenario 2) to be able to pause the world. That is because when the game checks the time, it will see that some have gone by.

To correctly pause the world, you need to take the time for the pause, go over each entity and compute the progress for that time, update its state it and mark it in pause. To resume, you need to take the time again, and go over each entity again, remove the pause mark and set the start time to time taken.

On the other hand, in scenario 2, you only need to stop updating. So, in scenario 2 you get the pause for free, but updating takes work. In Scenario 1 you get the updates for free but pausing takes work.

---

**You might still need Scenario 2**

Finally, there are things that need to be handled purely in the scenario 2. These are things that when completed will trigger another process or will require interaction with an external system.

A process A that starts another process B can be tricky to implement. You can do that, if the process A will start another process B in the future, you can set the starting time of the process B at the time when the process A will be completed. You can chain multiple processes this way.

If you also need processes to cancel other processes, that's harder. For example the process C will cancel the process D, then you would need to store the cancellation time for D, compare it to its completion time... and if it will be cancelled, then any effect the process D completing should be removed (for example if the process D was supposed to start the process E, then that should no longer happen).

The problem above gets even worse if the dependencies of the processes have interlaced branches (e.g. process A starts process B and C, process B will cancel process C, and process C will cancel process B).

Because of those complication, you might decide that it is better to implement that on the scenario 2.

The other example where you need scenario 2 is when you need to interact with an external system when the player is not logged in. For example, if the player let something crafting in your game, and you want the game to send a message to the player telling that it is completed... *even when the player is not logged in*. There is no way around it, you will have to implement that using the scenario 2.

---

## Conclusion

* you can implement everything in scenario 2 (like Minecraft does)
* you may also use scenario 1 as an optimization, letting thing work in scenario 2 when there is a player present
* there are things that can be implemented only in scenario 2

# Answer
> 0 votes
To be perfectly honest the "best" method is going to be a hybrid of the two, because there are things you absolutely have to store on the server. First, you absolutely must store what was planted and when on the server because otherwise when another player logs in they would have no knowledge of what another player planted.

So whether you calculate grow cycles on the client or not doesn't matter, what matters is that you know when something was planted and have the information required to figure out whether it's ready to be harvested or not.

For example, you have Player A plant seeds at 1:00pm and the server stores: what was planted, how much was planted, where it was planted, and a seed value for rain based on location and time. Then when Player B logs on to that area the client grabs all that info and runs the calculation based on the info to determine whether it's ready to harvest or not.

Since it's based on a predetermined seed you don't have issues with authentication, and you also avoid the performance hit of having the server globally calculate everything all the time (which isn't practical). It's all about how you design the database and your randomization engine for seeds and variance of weather (and how you limit/control it).

---
Tags: unity, mmo, client-server, databases, entity
---


title: 2D bone animation - point gun at mouse

text:
# Question
Title: 2D bone animation - point gun at mouse
How is this handled?

https://www.youtube.com/watch?v=egk3yD1w4Wo

It's some form of kinematics which I kinda understand and I have a very solid grip of trig, but I don't know how to start with having both hands attached to a single weapon with each arm moving independently and the torso also moving to accommodate extreme angles. How would one keep the gun completely static (It appears to have an origin/rotation point at the shoulder) while having the arms bend with the hands static on the gun?

Is the gun rotated to point at the mouse and that motion propagates back through the arms? Or does it figure out where the gun needs to be pointed and then rotate the arms to match?

How is the movement handled for the torso? Is the torso only rotated when the arms reach a limit?

etc.

As you can see I have a lot of questions. I'd just like a starting point to begin with, or someone to suggest a way to approach it all. An example or tutorial would be great if you could point me to one.

What I'd like to avoid is using a third party program like DragonBones, Spriter or Spine. I'd like to start at the beginning of the problem to get a fuller understanding of it all.

Thanks!

# Answer
So, I solved it. Turns out I just needed to get away from the problem a bit.

Just in case anyone else wants to replicate this, I got it working and I made a function in C# (Although it should be really easy to transpose it to any other language) that solves 2D arms. Arms being assumed to be made up of two segments with shoulder and elbow joints. All angles are in radians. It could probably be done better but this is what I've got in my test program:

```
public Vector2 SolveLimb(Vector2 startPosition, Vector2 endPosition, float     length)
{
    //startPosition is the where the first joint is. e.g. The shoulder.
    //endPosition is where the desired final position is for the last joint. e.g Where the hand should end up
    //length is the length of each arm segment. Could use separate values if you want arm segments of     different lengths

    //Get the direction vector between the hand and shoulder
    Vector2 dir = endPosition - startPosition;
    dir.Normalize();

    //Measure the distance between hand and shoulder to get length of one side of the triangle
    //The other two sides we already know because they're the lengths of the arm segments
    float distToEnd = Vector2.Distance(startPosition, endPosition);
    distToEnd = MathHelper.Clamp(distToEnd, 0, length * 2);

    //Lengths
    float ShoulderToHand = distToEnd;
    float ShoulderToElbow = ArmTexture.Width;
    float ElbowToHand = ArmTexture.Width;

    //Use the Law of Cosines to figure out what the two angles are that we want.
    //Helpful links: https://www.mathsisfun.com/algebra/trig-solving-sss-triangles.html
    //              https://en.wikipedia.org/wiki/Law_of_cosines
    //Math.Acos(angle) == Cos^1(angle)
    float ElbowA = (Square(ShoulderToElbow) + Square(ElbowToHand) - Square(ShoulderToHand)) / (2 * (ShoulderToElbow * ElbowToHand));
    float ElbowAngle = (float)Math.Acos(ElbowA);

    float ShoulderA = (Square(ShoulderToElbow) + Square(ShoulderToHand) - Square(ElbowToHand)) / (2 * (ShoulderToElbow * ShoulderToHand));
    float ShoulderAngle = (float)Math.Acos(ShoulderA);

    //Additional rotation that needs to be made to both arm segments
    float rot = (float)Math.Atan2(dir.Y, dir.X);
    Vector2 result;

    //Return the angles for the Shoulder and Elbow.
    //I used a Vector2 to return both numbers at the same time. x = Shoulder, y = Elbow
    //Added Pi to the elbow rotation to fix a problem where it was rotated 180 degrees incorrectly.
    //Probably messed up somewhere else, but it works
    result = new Vector2(ShoulderAngle + rot, ElbowAngle + ShoulderAngle + rot + (float)Math.PI);
    return result;
}

```

The rotation of the torso is really simple. I just did this:

```
Torso.Rotation = Gun.Rotation * 0.8f;

```

Hope this helps someone who stumbles across this.
> 1 votes

---
Tags: 2d, shooter, inverse-kinematics, bones
---


# Question
Title: procedurally combine a main character with weapons during animations
I need to find a way to programmatically place weapons for main character in right position of his body.

For example if I am using UMA to procedurally create humans and then use some pre-existing models of guns (10-20) of them. Now I need to find a way to place them correctly in the hand positions of the human model. I will use mixamo or IK to apply animations on the human character.

But is there any way to programmatically place the objects in the right positions? Probably by marking some joints?

I am looking at some efficient **approach** to begin with on this.

# Answer
The general approach here is to define some notion of "sockets" in the character skeleton. These need to encode position (where the attached thing should be) and rotation (which direction should the attached thing face), and as such can be represented as transforms relative to a parent, and as such are basically just specifically-named or designated bones in a skeletal rig. You can treat them separately if you like, however.

Then it's just a matter of creating some kind of attachment structure that pairs an object to another object at a specific socket or bone, and making sure the animation system knows to follow these attachments and apply the appropriated transform to the attached object during update of the skeleton.
> 3 votes

---
Tags: procedural-generation, procedural
---


# Question
Title: How can I obtain a triangle ID during rasterization?
I want to know the triangle ID of each rendered pixel is coming from. Is there a way to do this in OpenGL?

# Answer
If you are using glsl version 410 or higher, you can use

gl\_PrimitiveID

to get a triangle id per pixel on fragment shader. Hope this helps.
> 3 votes

---
Tags: opengl, rasterization
---


title: Get closest Child to cursor

text:
# Question
Title: Get closest Child to cursor
I'm currently rewoking my RTS cover system. This should highlight the closest coverspots from my mouse cursor and sent the units to these locations. everything works, but I can't get the closest sport, it always selects the sames ones, regardless to the mouse position.

These cover spots are child objects of the obstacle, that has this script attached.

This is my not working implementation of the idea:

```
 void Update()
    {

        var dist = Mathf.Abs(transform.position.z - Camera.main.transform.position.z);
        var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
        v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
        mousePos = v3Pos;
}

```

...

```
public void getPointDistances()
    {
        foreach (CoverPosition pos in coverPositions)
        {
            if (!pos.occupied)
            {
                pos.distanceToCursor = Vector3.Distance(pos.transform.position, mousePos);
            }
        }
        Array.Sort(coverPositions, delegate (CoverPosition x, CoverPosition y) { return y.distanceToCursor.CompareTo(x.distanceToCursor); });

    }

```

Later, I simply Iterate over the sorted array and make it visisible.

I'm woking on this for hours, but i cannot find, a solution why it always displays the same cover spots.

I hope, someone can find my (possibly stupid) error.

Edit:

I also tried this, but tata returned always the same values, regardless of my mouse positioning:

```
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
            mousePos = hit.transform.position;

```

# Answer
> 2 votes
It's hard to know exactly what the problem is without seeing how your scene is set up, but I suspect the issue is that your camera and your object are not even on the z-axis, which means that subtracting the z-vaules will not provide a true distance value to place the mouse pos in world space. Try the following:

```
    var dist = Vector3.Distance(transform.position, Camera.main.transform.position);
    var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
    v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
    Vector3 mousePos = v3Pos;

```

as for the edit, try using hit.point instead of hit.transform.position :

```
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit)){
        Debug.DrawRay(hit.point,Vector3.up,Color.green);
        mousePos = hit.point;
    }

```

That being said, I would suggest using the ScreenPointToRay method to generate a point in worldspace to do a distance check.

EDIT:

You also may be having an issue with your sorting method. If you do not assign a value to a CoverPosition.distanceToCursor, it's default value is going to be 0, meaning a distance of zero, and these coverpositions are going to be pushed to the front of the array.

try something like:

```
 foreach (CoverPosition pos in coverPositions)
    {
        if (!pos.occupied)
        {
            pos.distanceToCursor = Vector3.Distance(pos.transform.position, mousePos);
        } else {
            pos.distanceToCursor = Mathf.Infinity;
        }

    }
    Array.Sort(coverPositions, delegate (CoverPosition x, CoverPosition y) { return y.distanceToCursor.CompareTo(x.distanceToCursor); });
}

```

Though, it may be more efficient to simply reorder the objects when doing the distance check, instead of setting the distance property, then doing a Sort by property.

---
Tags: unity, c#, rts
---


# Question
Title: The simplest but most effective and intuitive way to implement Accuracy and Dodge chance in an RPG?
I am a university student and I have been tinkering with some RPG game ideas recently. One problem I am having is developing a proper mechanics or system of HIT or MISS chance in a monster-slashing game.

First of all, I want my stats to be simple and easy to interpret. So when the player opens his offensive and defensive stat menu he will see something like this:

Accuracy: 90%

Dodge chance (or Evasion rate): 10%

One solution I come up with was this system:

Hit chance = (Accuracy - Dodge Chance)

For example, my character has a base Accuracy of 80%, the monster he is slaying has a Dodge Chance of 10%. Therefore, when I hit the monster I have a 70% chance to make the hit.

Notice that in this system, I allow the Accuracy and Dodge Chance to exceed 100% by means of gearing and buffing. So there can be scenarios like: My character has a base Accuracy of 80%. He has a weapon with a stat line +20% accuracy and a ring with a stat line +10% accuracy equipped. He also has a skill that says "+30% accuracy for 10 seconds". So when my character equips those items and activates the buff skill, he should see an effective Accuracy of 140% in his stat.

So when this character slays a monster with only 20% Dodge chance he will always guarantee a hit. This makes sense because he should be rewarded for choosing this item and this skill (or this build basically).

Of course, there will be types of monster where there Dodge Chance is high, or incredibly high (maybe 200%) for a super rare creature which could drop lots of legendaries when slain which would encourage players to equip specific builds in order to hunt them.

My question is that, is there a better and more intuitive system than this? I saw some post suggest that we calculate hit chance by:

Hit chance = ((Accuracy - Dodge Chance)/Accuracy)\*100 (%)

How is this different than my formula? and which one is more consistent in an RPG? and which would make players feel better playing and building their character? because I have seen some players get frustrated when they miss a crucial hit/skill.

Of course, what are other popular systems regarding HIT and MISS in RPGs which do not rely significantly on RNG but, ultimately, on the players' decisions of choosing their gear, skills and build?

# Answer
In your system there will be situations where either all attacks of combatant A on combatant B will fail or situations where all attacks will succeed. If that is your design goal, then go for it.

The formula `((Accuracy - Dodge Chance)/Accuracy)*100 (%)` is far less intuitive than your formula, but will always give a small chance to miss, even if the accuracy stat is far larger than the dodge stat. But you can still be "safe" if the defenders dodge is more or equal the attackers accuracy. Whether that's good or bad depends on your design goals.

Another formula is to just roll a random number between 0 and the attacker's accuracy and a second random number between 0 and the defender's dodge and see who rolls higher. That way there is always a small chance to dodge or miss no matter how different the stats are. In this case you shouldn't add a percent-sign after your accuracy and dodge stats, because they have nothing to do with percentage anymore.

Regarding the question "What do the players want": During some playtests with a Strategy-RPG I developed a while ago I found that the players usually prefer if their own characters hit almost all the time, even if their characters do less damage and their damage output is less reliable. Most players felt frustrated whenever they saw one of their characters miss. This was especially frustrating when a player lost a battle due to a random miss in a very important situation. They felt like they lost because they were betrayed by the RNG, not because they played bad. I guess that's mostly because the players don't have a way to directly influence whether or not their characters hit, so seeing a miss is a punishment even though they didn't do anything wrong.

In the end I got rid of the accuracy stat and made all attacks hit all the time. To still have some randomness I added more random spread to the damage calculation. Players found it far less frustrating to see their characters do very little damage than no damage at all.

But every game is different. Your game might be more enjoyable with random misses than mine. The only way to find out is to test play, analyze, tweak and test play again and again.
> 3 votes

# Answer
There are a bunch of ways to implement systems like this, but one thing really stands out to me after reading your post: hit chance and dodge chance are not a single calculation and shouldn't be treated as such.

What I mean is this: if I were attempting to shoot a target with a bow & arrow what are the factors involved in figuring out whether I might hit it?

* What is my skill with a bow & arrow
* What is the quality/accuracy of the bow & arrow
* How far away am I from the target
* Is the target moving
* Is the target actively trying to avoid being hit

So if you were applying those concepts to an RPG what you'd probably do is give the player a base accuracy determined by their level and skills. Then you'd modify that based on their equipment (weapon, stats, etc) and that would determine their overall accuracy in a "perfect" environment. Then you'd create a target and they would have a base chance to dodge determined by their level/skills and modified by their equipment/stats.

When you actually calculate the hit you would FIRST determine if the player would hit the target if it was completely stationary and not dodging. Keep in mind that when calculating this you need to take into account any relevant factors such as distance and environment (weather).

If the player misses then it doesn't really matter whether the target dodges or not (unless you include "critical mishaps" where the target jumps into the way of a missed shot, I don't advise doing that for complexity reasons).

If the player *would* hit the target then you need to calculate whether or not the target dodges, which would be determined by the dodge chance relative to any modifiers (the relative accuracy of the player, distance, etc).

So if a player has a 100% chance to hit and is at short range shooting at a stationary target then you might apply a penalty to the dodge chance of the target (if I'm shooting an arrow at someone from 10 feet away using a compound bow it's highly unlikely they would have the time to react, let alone dodge).

That could mean an effective dodge chance of 0%, but it remains a separate calculation AFTER you figure out whether the player would hit initially. Also, you could use the "quality" of the shot to influence the dodge chance as well. For example, if you had a 50% chance to hit and rolled a 100 sided dice you might treat a 100 as a perfect shot and a 51 as barely on target and have that relative value impact the dodge chance.

Just some food for thought...
> -1 votes

---
Tags: game-design, rpg, statistics, mathematics
---


# Question
Title: What's a way to implement a flexible buff/debuff system?
**Overview:**

Lots of games with RPG-like statistics allow for character "buffs", ranging from simple "Deal 25% extra damage" to more complicated things like "Deal 15 damage back to attackers when hit."

The specifics of each type of buff aren't really relevant. I'm looking for a (presumably object-oriented) way to handle arbitrary buffs.

**Details:**

In my particular case, I have multiple characters in a turn-based battle environment, so I envisioned buffs being tied to events like "OnTurnStart", "OnReceiveDamage", etc. Perhaps each buff is a subclass of a main Buff abstract class, where only the relevant events are overloaded. Then each character could have a vector of buffs currently applied.

Does this solution make sense? I can certainly see dozens of event types being necessary, it feels like making a new subclass for each buff is overkill, and it doesn't seem to allow for any buff "interactions". That is, if I wanted to implement a cap on damage boosts so that even if you had 10 different buffs which all give 25% extra damage, you only do 100% extra instead of 250% extra.

And there's more complicated situations that ideally I could control. I'm sure everyone can come up with examples of how more sophisticated buffs can potentially interact with each other in a way that as a game developer I may not want.

As a relatively inexperienced C++ programmer (I generally have used C in embedded systems), I feel like my solution is simplistic and probably doesn't take full advantage of the object-oriented language.

Thoughts? Has anyone here designed a fairly robust buff system before?

**Edit: Regarding Answer(s):**

I selected an answer primarily based on good detail and a solid answer to the question I asked, but reading the responses gave me some more insight.

Perhaps unsurprisingly, the different systems or tweaked systems seem to apply better to certain situations. What system works best for my game will depend on the types, variance, and number of buffs I intend to be able to apply.

For a game like Diablo 3 (mentioned below), where nearly any bit of equipment can change a buff's strength, the *buffs are just character stats* system seems like a good idea whenever possible.

For the turn-based situation I'm in, the event-based approach may be more suitable.

In any case, I'm still hoping someone comes along with a fancy "OO" magic bullet which will allow for me to apply a *+2 move distance per turn* buff, a *deal 50% of damage taken back to the attacker* buff, and a *automatically teleport to a nearby tile when attacked from 3 or more tiles away* buff in a single system without turning a *+5 strength* buff into its own subclass.

I think the closest thing is the answer I marked, but the floor is still open. Thanks to everyone for the input.

# Answer
This is a complicated issue, because you're talking about a few different things that (these days) get lumped together as 'buffs':

* modifiers to a player's attributes
* special effects that happen on certain events
* combinations of the above.

I always implement the first with a list of active effects for a certain character. Removal from the list, whether based on duration or explicitly is fairly trivial so I won't cover that here. Each Effect contains a list of attribute modifiers, and can apply it to the underlying value via simple multiplication.

Then I wrap it with functions to access the modified attributes. eg.:

```
def get_current_attribute_value(attribute_id, criteria):
    val = character.raw_attribute_value[attribute_id]
    # Accumulate the modifiers
    for effect in character.all_effects:
        val = effect.apply_attribute_modifier(attribute_id, val, criteria)
    # Make sure it doesn't exceed game design boundaries
    val = apply_capping_to_final_value(val)
    return val

class Effect():
    def apply_attribute_modifier(attribute_id, val, criteria):
        if attribute_id in self.modifier_list:
            modifier = self.modifier_list[attribute_id]
            # Does the modifier apply at this time?
            if modifier.criteria == criteria:
                # Apply multiplicative modifier
                return val * modifier.amount
        else:
            return val

class Modifier():
    amount = 1.0 # default that has no effect
    criteria = None # applies all of the time

```

That lets you apply multiplicative effects easily enough. If you need additive effects also, decide what order you're going to apply them in (probably additive last) and run through the list twice. (I'd probably have separate modifier lists in Effect, one for multiplicative, one for additive).

The criteria value is to let you implement "+20% vs Undead" - set the UNDEAD value on the Effect and only pass the UNDEAD value to `get_current_attribute_value()` when you're calculating a damage roll against an undead foe.

Incidentally, I wouldn't be tempted to try and write a system that applies and unapplies values directly to the underlying attribute value - the end result is that your attributes are very likely to drift away from the intended value due to error. (eg. if you multiply something by 2, but then cap it, when you divide it by 2 again, it'll be lower than it started with.)

As for event-based effects, such as "Deal 15 damage back to attackers when hit", you can add methods on the Effect class for that. But if you want distinct and arbitrary behaviour (eg. some effects for the above event might reflect damage back, some might heal you, it might teleport you away randomly, whatever) you'll need custom functions or classes to handle it. You can assign functions to event handlers on the effect, then you can just call the event handlers on any active effects.

```
# This is a method on a Character, called during combat
def on_receive_damage(damage_info):
    for effect in character.all_effects:
        effect.on_receive_damage(character, damage_info)

class Effect():
    self.on_receive_damage_handler = DoNothing # a default function that does nothing
    def on_receive_damage(character, damage_info):
        self.on_receive_damage_handler(character, damage_info)

def reflect_damage(character, damage_info):
    damage_info.attacker.receive_damage(15)

reflect_damage_effect = new Effect()
reflect_damage_effect.on_receive_damage_handler = reflect_damage
my_character.all_effects.add(reflect_damage_effect)

```

Obviously your Effect class will have an event handler for every type of event, and you can assign handler functions to as many as you need in each case. You don't need to subclass Effect, as each one is defined by the composition of the attribute modifiers and event handlers it contains. (It will probably also contain a name, a duration, etc.)
> 37 votes

# Answer
In a game that I worked on with a friend for a class we made a buff/debuff system for when the user gets trapped in tall grass and speed-up tiles and what not, and some minor things like bleeds and poisons.

The idea was simple, and while we applied it in Python, it was rather effective.

Basically, here is how it went :

* User had a list of currently applied buffs and debuffs (note that a buff and debuff are relatively the same, it's just the effect that has a different outcome)
* Buffs have a variety of attributes such as duration, name, and text for displaying information, and time alive. The important ones are time alive, duration, and a reference to the actor this buff is applied to.
* For the Buff, when it is attached to the player via player.apply(buff/debuff), it would call a start() method, this would apply the critical changes to the player such as increasing speed or slowing down.
* We would then iterate through each buff in an update loop and the buffs would update, this would increase their time alive. Subclasses would implement things like poisoning the player, giving the player HP over time, etc.
* When the buff was done for, meaning timeAlive \>= duration, the update logic would remove the buff and call a finish() method, which would vary from removing the speed limitations on a player to causing a small radius (think of a bomb effect after a DoT)

Now how to actually apply buffs from the world is a different story. Here is my food for thought though.
> 25 votes

# Answer
I am not sure if you are reading this still but I have struggled with this sort of problem for a long time.

I've designed numerous different types of affect systems. I'll briefly go over them now. This is all based on my experience. I don't claim to know all of the answers.

---

***Static Modifiers***

This type of system mostly relies on simple integers to determine any modifications. For example, +100 to Max HP, +10 to attack and so on. This system could also handle percents as well. You just need to make sure that the stacking doesn't get out of control.

I never really cached the generated values for this type of system. For example, if I wanted to display the max health of something, I would generate the value on the spot. This prevented things from being error prone and just easier to understand for everyone involved.

(I work in Java so the what follows is Java based but it should work with some modifications for other languages) This system can easily be done using enums for the modification types, and then integers. The end result can be placed into some sort of collection that has key,value ordered pairs. This will be fast lookup and calculations, so the performance is very good.

Overall, it works very well with just flat out static modifiers. Though, code must exist in the proper places for the modifiers to be used: getAttack, getMaxHP, getMeleeDamage, and so on and so forth.

Where this method fails (for me) is very complex interaction between buffs. There isn't a real easy way to have interaction except by ghettoing it a up a bit. It does have some simple interaction possibilities. In order to do that, you must make a modification to the way you store the static modifiers. Instead of using an enum as the key, you use a String. This String would be the Enum name + extra variable. 9 times out of 10, the extra variable is not used, so you still retain the enum name as the key.

Let's do a quick example: If you wanted to be able to modify damage against undead creatures, you could have an ordered pair like this: (DAMAGE\_Undead, 10) The DAMAGE is the Enum and the Undead is the extra variable. So during your combat, you can do something like:

```
dam += attacker.getMod(Mod.DAMAGE + npc.getRaceFamily()); //in this case the race family would be undead

```

Anyways, it works fairly well and is fast. But it fails at complex interactions and having “special” code everywhere. For example, consider the situation of “25% chance to teleport on death”. This is a “fairly” complex one. The above system can handle it, but not easily, as you need the following:

1. Determine if the player has this mod.
2. Somewhere, have some code to execute the teleportation, if successful. The location of this code is a discussion in itself!
3. Get the right data from the Mod map. What does the value mean? Is it the room where they teleport too? What if a player has two teleport mods on them?? Won't the amounts get added together?????? FAILURE!

So this brings me to my next one:

---

***The Ultimate Complex Buff System***

I once tried to write a 2D MMORPG by myself. This was an awful mistake but I learned a lot!

I rewrote the affect system 3 times. The first one used a less powerful variation of the above. The second one was what I'm going to talk about.

This system had a series of classes for each modification, so things like: ChangeHP, ChangeMaxHP, ChangeHPByPercent, ChangeMaxByPercent. I had a million of these guys – even things like TeleportOnDeath.

My classes had things that would do the following:

* applyAffect
* removeAffect
* checkForInteraction \<--- important

Apply and remove explain themselves (though for things like percents, the affect would keep track of how much it increased the HP by to ensure when the affect wore off, it'd only remove the amount it added. This was buggy, lol, and took me a long time to make sure it was right. I still didn't get a good feeling about it.).

The checkForInteraction method was a horrodeously complex piece of code. In each of the affects (ie: ChangeHP) classes, it would have code to determine if this should be modified by the input affect. So for example, if you had something like....

* Buff 1: Deals 10 Fire damage on attack
* Buff 2: Increases all fire damage by 25%.
* Buff 3: Increases all fire damage by 15.

The checkForInteraction method would handle all of these affects. In order to do this, each affect on ALL of the players near by had to be checked!! This is because the type of affects I had dealt with multiple players over a span of an area. This means the code NEVER HAD any special statements like above - “if we just died, we should check for teleport on death”. This system would automatically handle it correctly at the right time.

Trying to write this system took me like 2 months and made by head explode several times. HOWEVER, it was REALLY powerful and could do an insane amount of stuff – especially when you take into account the following two facts for abilities in my game: 1. They had target ranges (ie: single, self, group only, PB AE self, PB AE target, targetted AE, and so on). 2. Abilities could have more than 1 affect on them.

As I mentioned above, this was the 2nd of 3rd affect system for this game. Why did I move away from this?

*This system had the worst performance I've ever seen!* It was awfully slow as it had to do so much checking for each thing that went on. I tried to improve it, but deemed it a failure.

So we come to my third version (and another type of buff system):

---

***Complex Affect Class with Handlers***

So this is pretty much a combination of the first two: We can have static variables in an Affect class that contains a lot of functionality and extra data. Then just call handlers (for me, pretty much some static utility methods instead of subclasses for specific actions. But I'm sure you could go with subclasses for actions if you wanted too) when we want to do something.

The Affect class would have all of the juicy good stuffs, like target types, duration, number of uses, chance to execute and so on and so forth.

We would still have to add special codes in order to handle the situations, for example, teleport on death. We would still have to check for this in the combat code manually, and then if it existed, we would get a list of affects. This list of affects contains all of the currently applied affects on the player that dealt with teleporting on death. Then we would just look at each one and check to see if it executed and was successful (We'd stop at the first successful one). It it was successful, we'd just call the handler to take care of this.

Interaction can be done, if you want too. It'd just have to write the code to look for specific buffs on the players/etc. Because it has good performance (see below), it should fairly be efficient to do that. It just would need more complex handlers and so on.

So it has a lot of the performance of the first system and still a lot of complexity like the second (but not AS much). In Java at least, you can do some tricky things to get the performance of almost the first one in MOST cases (ie: having an enum map (http://docs.oracle.com/javase/6/docs/api/java/util/EnumMap.html) with Enums as the keys and ArrayList of affects as the values. This lets you to see if you quickly have affects \[since the list would be 0 or the map wouldn't have the enum\] and not having to continually iterate over player's affect lists for no reason. I don't mind iterating over affects if we need them at this time. I'll optimize later if it becomes a problem).

I'm currently re-opening (rewriting the game in Java instead of the FastROM code base it was originally in) my MUD that ended in 2005 and I have recently ran into how do I want to implement my buff system? I am going to be using this system because it worked nicely in my previous failed game.

Well, hopefully someone, somewhere, will find a few of these insights useful.
> 14 votes

# Answer
A different class (or addressable function) for each buff is not overkill if the behavior of those buffs is different from one another. One thing would be having +10% or +20% buffs (that, of course, would be better represented as two objects of the same class), other would be implementing wildly different effects that would require custom code anyway. However, I believe it's better to have **standard ways of customizing the game logic** instead of letting each buff do whatever it pleases (and possibliy interfering with each other in unforeseen ways, disturbing game balance).

I'd suggest dividing each "attack cycle" into steps, where each step has a base value, an ordered list of modifications that can be applied to that value (maybe capped), and a final cap. Each modification has an identity transformation as default, and can be influenced by zero or more buffs/debuffs. The specifics of each modification would depend on the step applied. How the cycle is implemented is up to you (including the option of an event-driven architecture, as you've been discussing).

One example of attack cycle could be:

* calculate player attack (base + mods);
* calculate opponent defense (base + mods);
* do the difference (and apply mods) and determine the base damage;
* calculate any parry/armor effects (mods on base damage) and apply damage;
* calculate any recoil effect (mods on base damage) and apply to the attacker.

The important thing to note is that the **earlier** in the cycle a buff is applied the **more effect it will have in the outcome**. So, if you want a more "tactical" combat (where the player skill is more important than the character level) create many buffs/debuffs on the basic stats. If you want a more "balanced" combat (where the level matters more - important in MMOGs to limit rate of progress) only use buffs/debuffs later in the cycle.

The distinction between "Modifications" and "Buffs" I mentioned earlier has a purpose: decisions about rules and balance can be implemented on the former, so any changes on those don't need to reflect in changes to every class of the latter. OTOH, the numbers and kinds of buffs are only limited by your imagination, since each of them can express their desired behavior without having to take into account any possible interaction between them and the others (or even the existence of others at all).

So, answering the question: don't create a class for each Buff, but one for each (type of) Modification, and tie the Modification to the attack cycle, not to the character. The buffs can be simply a list of (Modification,key,value) tuples, and you can apply a buff to a character by simply adding/removing it to the character's set of buffs. This also reduces the window for error, since the character's stats **don't need to be changed** at all when the buffs are applied (so there's less risk to restore a stat to the wrong value after a buff expires).
> 7 votes

# Answer
I worked on a small MMO and all items, powers, buffs etc had 'effects'. An effect was a class that had variables for 'AddDefense', 'InstantDamage', 'HealHP', etc. The powers, items, etc would handle the duration for that effect.

When you cast a power or put on an item it would apply the effect to the character for the specified duration. Then the main attack, etc calculations would take into account the applied effects.

For example, you have a buff that adds defense. There would be at minimum a EffectID and Duration for that buff. When casting it, it would apply the EffectID to the character for the specified duration.

Another example for an item, would have the same fields. But the duration would be infinite or until the effect is removed by taking the item off the character.

This method allows you to iterate over a list of effects that are currently applied.

Hope I explained this method clearly enough.
> 3 votes

# Answer
I don't know if you are still reading it, but here is how I'm doing it now (code is based on UE4 and C++). After pondering on the problem for more than two weeks (!!), I finally found this:

http://gamedevelopment.tutsplus.com/tutorials/using-the-composite-design-pattern-for-an-rpg-attributes-system--gamedev-243

And I thought, that well, encapsulating single attribute within class/struct is not that bad idea after all. Keep in mind though, that I'm taking really big advantage of UE4 build in code reflection system, so without some rework, this might not be suitable everywhere.

In anyway, I started from wrapping attribute into single struct:

```
USTRUCT(BlueprintType)
struct GAMEATTRIBUTES_API FGAAttributeBase
{
    GENERATED_USTRUCT_BODY()
public:
    UPROPERTY()
        FName AttributeName;
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Value")
        float BaseValue;
    /*
        This is maxmum value of this attribute.
    */
    UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Value")
        float ClampValue;
protected:
    float BonusValue;
    //float OldCurrentValue;
    float CurrentValue;
    float ChangedValue;

    //map of modifiers.
    //It could be TArray, but map seems easier to use in this case
    //we need to keep track of added/removed effects, and see
    //if this effect affected this attribute.
    TMap<FGAEffectHandle, FGAModifier> Modifiers;

public:

    inline float GetFinalValue(){ return BaseValue + BonusValue; };
    inline float GetCurrentValue(){ return CurrentValue; };
    void UpdateAttribute();

    void Add(float ValueIn);
    void Subtract(float ValueIn);

    //inline float GetCurrentValue()
    //{
    //  return FMath::Clamp<float>(BaseValue + BonusValue + AccumulatedBonus, 0, GetFinalValue());;
    //}

    void AddBonus(const FGAModifier& ModifiersIn, const FGAEffectHandle& Handle);
    void RemoveBonus(const FGAEffectHandle& Handle);

    void InitializeAttribute();

    void CalculateBonus();

    inline bool operator== (const FGAAttributeBase& OtherAttribute) const
    {
        return (OtherAttribute.AttributeName == AttributeName);
    }

    inline bool operator!= (const FGAAttributeBase& OtherAttribute) const
    {
        return (OtherAttribute.AttributeName != AttributeName);
    }

    inline bool IsValid() const
    {
        return !AttributeName.IsNone();
    }
    friend uint32 GetTypeHash(const FGAAttributeBase& AttributeIn)
    {
        return AttributeIn.AttributeName.GetComparisonIndex();
    }
};

```

It's still not finished but the base idea, is that this struct keep track of it's internal state. Attributes can be modified only by Effects. Trying to modify them directly is unsafe and not exposed to designers. I'm assuming that everything, that can interact with attributes is Effect. Including flat bonuses from items. When new item is equipped, new effect (along with handle) is created, and it is added to dedicated map, which handle infinite duration bonuses (those that must be manually removed by player). When new Effect is being applied, new Handle for it is created (handle is just int, wrapped with struct), and then that handle is passed all around as a means to interacting with this effect, as well as keep track if the effect is still active. When effect is removed, it's handle is broadcasted to all interested objects, for clean up.

The real important part of this is TMap (TMap is hashed map). FGAModifier is very simple struct:

```
struct FGAModifier
{
    EGAAttributeOp AttributeMod;
    float Value;
};

```

It contains type of modification:

```
UENUM()
enum class EGAAttributeOp : uint8
{
    Add,
    Subtract,
    Multiply,
    Divide,
    Set,
    Precentage,

    Invalid
};

```

And Value which is final calculated value we are going to apply to attribute.

We add new effect using simple function, and then call:

```
void FGAAttributeBase::CalculateBonus()
{
    float AdditiveBonus = 0;
    auto ModIt = Modifiers.CreateConstIterator();
    for (ModIt; ModIt; ++ModIt)
    {
        switch (ModIt->Value.AttributeMod)
        {
        case EGAAttributeOp::Add:
            AdditiveBonus += ModIt->Value.Value;
                break;
            default:
                break;
        }
    }
    float OldBonus = BonusValue;
    //calculate final bonus from modifiers values.
    //we don't handle stacking here. It's checked and handled before effect is added.
    BonusValue = AdditiveBonus;
    //this is absolute maximum (not clamped right now).
    float addValue = BonusValue - OldBonus;
    //reset to max = 200
    CurrentValue = CurrentValue + addValue;
}

```

This function is supposed to recalculate entire stack of bonuses, each time effect is added or removed. Function is still not finished (as you can see), but you can get the general idea.

My biggest gripe right now is handling Damaging/Healing attribute (without involving recalculating entire stack), I think I have this somewhat solved, but it still require more testing to be 100%.

In anycase Atttributes are defined like this(+Unreal macros, omitted here):

```
FGAAttributeBase Health;
FGAAttributeBase Energy;

```

etc.

Also I'm not 100% sure about handling CurrentValue of attribute, but it should work. They way it is now.

In any case I hope it will save some people head caches, not sure if this is best or even good solution, but I like it more, than tracking effects independently of attributes. Making each attribute tracking it's own state is much easier in this case, and should be less error prone. There is essentially only one point of failure, which is fairly short and simple class.
> 3 votes

# Answer
1. If you´re a unity user, here is something to get started: http://www.stevegargolinski.com/armory-a-free-and-unfinished-stat-inventory-and-buffdebuff-framework-for-unity/

Im using ScriptableOjects as buffs/spells/talents

```
public class Spell : ScriptableObject
{
    public SpellType SpellType = SpellType.Ability;
    public SpellTargetType SpellTargetType = SpellTargetType.SingleTarget;
    public SpellCategory SpellCategory = SpellCategory.Ability;
    public MagicSchools MagicSchool = MagicSchools.Physical;
    public CharacterClass CharacterClass = CharacterClass.None;
    public string Description = "no description available";
    public SpellDragType DragType = SpellDragType.Active;
    public bool Active = false;
    public int TargetCount = 1;
    public float CastTime = 0;
    public uint EffectRange = 3;
    public int RequiredLevel = 1;
    public virtual void OnGUI()
    {
    }
}

```

using UnityEngine; using System.Collections.Generic;

public enum BuffType { Buff, Debuff } \[System.Serializable\] public class BuffStat { public Stat Stat = Stat.Strength; public float ModValueInPercent = 0.1f; }

```
public class Buff : Spell
{
    public BuffType BuffType = BuffType.Buff;
    public BuffStat[] ModStats;
    public bool PersistsThroughDeath = false;
    public int AmountPerTick = 3;
    public bool UseTickTimer = false;
    public float TickTime = 1.5f;
    [HideInInspector]
    public float Ticktimer = 0;
    public float Duration = 360; // in seconds
    public float ModifierPerStack = 1.1f;
    [HideInInspector]
    public float Timer = 0;
    public int Stack = 1;
    public int MaxStack = 1;
}

```

BuffModul:

```
using System;
using RPGCore;
using UnityEngine;

public class Buff_Modul : MonoBehaviour
{
    private Unit _unit;

    // Use this for initialization
    private void Awake()
    {
        _unit = GetComponent<Unit>();
    }

    #region BUFF MODUL

    public virtual void RUN_BUFF_MODUL()
    {
        try
        {
            foreach (var buff in _unit.Attr.Buffs)
            {
                CeckBuff(buff);
            }
        }
        catch(Exception e) {throw new Exception(e.ToString());}
    }

    #endregion BUFF MODUL

    public void ClearBuffs()
    {
        _unit.Attr.Buffs.Clear();
    }

    public void AddBuff(string buffName)
    {
        var buff = Instantiate(Resources.Load("Scriptable/Buff/" + buffName, typeof(Buff))) as Buff;
        if (buff == null) return;
        buff.name = buffName;
        buff.Timer = buff.Duration;
        _unit.Attr.Buffs.Add(buff);
        foreach (var buffStat in buff.ModStats)
        {
            switch (buff.BuffType)
            {
                case BuffType.Buff:
                    _unit.Attr.AddBuffStatValue(buffStat.Stat, Mathf.RoundToInt((_unit.Attr.StatsBase[buffStat.Stat] + _unit.Attr.StatsItem[buffStat.Stat]) * buffStat.ModValueInPercent));
                    break;
                case BuffType.Debuff:
                    _unit.Attr.RemoveBuffStatValue(buffStat.Stat, Mathf.RoundToInt((_unit.Attr.StatsBase[buffStat.Stat] /*+ unit.character.StatsItem[_stat.stat]*/) * buffStat.ModValueInPercent));
                    break;
            }
            Core.StatController(_unit.Attr, buffStat.Stat);
        }
    }

    public void RemoveBuff(Buff buff)
    {
        foreach (var buffStat in buff.ModStats)
        {
            switch (buff.BuffType)
            {
                case BuffType.Buff:
                    _unit.Attr.RemoveBuffStatValue(buffStat.Stat, Mathf.RoundToInt((_unit.Attr.StatsBase[buffStat.Stat] + _unit.Attr.StatsItem[buffStat.Stat]) * buffStat.ModValueInPercent));
                    break;
                case BuffType.Debuff:
                    _unit.Attr.AddBuffStatValue(buffStat.Stat, Mathf.RoundToInt((_unit.Attr.StatsBase[buffStat.Stat]  /*+ unit.character.StatsItem[_stat.stat]*/) * buffStat.ModValueInPercent));
                    break;
            }
            Core.StatController(_unit.Attr, buffStat.Stat);
        }
        _unit.Attr.Buffs.Remove(buff);
    }

    void CeckBuff(Buff buff)
    {
        buff.Timer -= Time.deltaTime;
        if (!_unit.IsAlive && !buff.PersistsThroughDeath)
        {
            if (buff.ModStats != null)
                foreach (var stat in buff.ModStats)
                {
                    _unit.Attr.StatsBuff[stat.Stat] = 0;
                }

            RemoveBuff(buff);
        }
        if (_unit.IsAlive && buff.Timer <= 0)
        {
            RemoveBuff(buff);
        }
    }
}

```
> 2 votes

# Answer
I know this is fairly old but it was linked in a newer post and I have some thoughts on it I'd like to share. Unfortunately I don't have my notes with me at the moment, so I'll try to give a general overview of what I'm talking about and I'll edit in the details and some example code when I have it in front of me.

First, I think that from a design perspective most people are getting too caught up in what types of buffs can be created and how they are applied and forgetting the basic principles of object oriented programming.

What do I mean? It doesn't really matter whether something is a buff or a debuff, they are both modifiers that just affect *something* in either a positive or negative manner. The code doesn't care which is which. For that matter it doesn't ultimately matter whether something is adding stats or multiplying them, those are just different operators and again the code doesn't care which is which.

So where am I going with this? That designing a good (read: simple, elegant) buff/debuff class isn't all that difficult, what's hard is designing the systems that calculate and maintain the game state.

If I were designing a buff/debuff system here are some things I'd consider:

* A buff/debuff class to represent the effect itself.
* A buff/debuff type class to contain the information about what the buff affects and how.
* Characters, Items and possibly Locations would all need to have a list or collection property to contain buffs and debuffs.

Some specifics for what buff/debuff types should contain:

* Who/what it can be applied to, IE: player, monster, location, item, etc.
* What type of effect it is (positive, negative), whether it is multiplicative or additive, and what type of stat it impacts, IE: attack, defense, movement, etc.
* When it should be checked (combat, time of day, etc).
* Whether it can be removed, and if so how it can be removed.

That's just a start, but from there you're just defining what you want and acting on it using your normal game state. For example, say you wanted to create a cursed item that reduces movement speed...

As long as I have put the proper types in place it's simple to create a buff record that says:

* Type: Curse
* ObjectType: Item
* StatCategory: Utility
* StatAffected: MovementSpeed
* Duration: Infinite
* Trigger: OnEquip

And so forth, and when I create a buff I just assign it the BuffType of Curse and everything else is up to the engine...
> 2 votes

# Answer
This was an actual question for me. I have one idea about it.

1. As previously said, we need to implement a `Buff` list and a logic updater for the buffs.
2. We then need to change all specific player settings every frame in subclasses of the `Buff` class.
3. We then get the current player settings from changable settings field.

---

```
class Player {
  settings: AllPlayerStats;

  private buffs: Array<Buff> = [];
  private baseSettings: AllPlayerStats;

  constructor(settings: AllPlayerStats) {
    this.baseSettings = settings;
    this.resetSettings();
  }

  addBuff(buff: Buff): void {
    this.buffs.push(buff);
    buff.start(this);
  }

  findBuff(predcate(buff: Buff) => boolean): Buff {...}

  removeBuff(buff: Buff): void {...}

  update(dt: number): void {
    this.resetSettings();
    this.buffs.forEach((item) => item.update(dt));
  }

  private resetSettings(): void {
    //some way to copy base to settings
    this.settings = this.baseSettings.copy();
  }
}

class Buff {
    private owner: Player;

    start(owner: Player) { this.owner = owner; }

    update(dt: number): void {
      //here we change anything we want in subclasses like
      this.owner.settings.hp += 15;
      //if we need base value, just make owner.baseSettings public but don't change it! only read

      //also here logic for removal buff by time or something
    }
}

```

In this way, it can be easy to add new player stats, with no change to the logic of the `Buff` subclasses.
> 1 votes

---
Tags: c++, game-mechanics, effect-modifier
---


title: How to Properly Type My Curve's Formula

text:
# Question
Title: How to Properly Type My Curve's Formula
I'm creating an RPG game (using C# in Unity API) that uses a leveling system. I went to the Desomos Online Graphing Calculator and created the following curve representing the levels based on experience: https://www.desmos.com/calculator/bsvkba4qg1. Note that the Y-intercept is at approximately (0, 1).

My `Character` class has the following fields representing the experience curve from above:

```
public float experience { get; set; }

public int level {
    get
    {
        float level = experience / 120;
        level += 1.123f;
        level = Mathf.Log(level);
        level *= 20;
        return Mathf.FloorToInt(level);
    }
}

```

However, when the game begins and `experience` defaults to 0 as floats do, `level` returns 2. When `experience` is `100`, `level` returns `13`. Clearly there is some error on my part. Have I entered my formula wrong? If so, how can I fix it, and if not, what else might be the problem?

# Answer
In your Desmos graph, you are using log base 10, however your unity function is using log base e (natural log, often abbreviated ln). To specify that you want log base 10, you need to add a second argument like the example below. See Mathf.Log() for details.

```
 level = Mathf.Log(level,10);

```
> 1 votes

---
Tags: unity, c#, curves
---


# Question
Title: Most efficient way of communication between "unfamiliar" game objects?
Title could look vague, so here's what I actually mean.

Three groups of people are walking in the city. These are Guards, Thieves and Citizens. Something has happened in the city, Thief have stolen a pocket from a Citizen, the Guard walking around was close enough to see the crime, so now he's chasing Thief.

So here's the question, how that chain would work from execution perspective? We can imagine there is a some kind of StateCheckingObject placed in the world. When Thief steals a pocket, it's class (or Citizen's class ) would broadcast a message to the StateCheckingObject. After StateCheckingObject is aware of crime it would broadcast message to the Guards walking around making them aware of crime.

Well, broadcasting stuff doesn't look complex, that could be a simple event dispatcher. But how would Thieves, Citizens and Guards hold a reference to StateCheckingObject? And what StateCheckingObject should even look like? Should it somewhere in the level? Should other object access it when spawned with GetAllObjectOfClass(StateCheckingObject)? That could be a heavy task for system since iterating over all level objects is not very efficient.

The issue looks pretty similar to GTA where events are broadcaster to nearby police cars when crime is happening, but what would make a broadcast?

Edit: **lilotop** suggested a trigger box solution and I've realised I haven't explained the idea why I would want to make state checking system.

Some actions happening in the world should be stored somewhere. I.E. after Citizen got robbed StateChecker would get aware of it and store bool CitizenGotRobbed. That boolean would later be used in maybe some kind of dialogue adding new branch to guard dialogue.

# Answer
> 3 votes
Here's an idea.

When a citizen gets robbed, have the citizen store a `report`:

```
public class report{
Thief offender;
Time timeOfOccurrence;
Citizen victim;
Vector3 location;
Item[] stolenItems;
}

```

After the citizen gets robbed, have the citizen run around looking for a `guard`. It could be random running until the citizen finds a `guard` via `Physics.OverlapSphere` or any other similar method if you're not using Unity (to simulate the effect of not knowing where the `guard` is) or they could run to the nearest Guard Post where a `guard` is usually standing.

When the `citizen` finds a `guard`, it tags them and the `guard` and `citizen` move toward each other. Once within range, the `citizen` gives it's `report` to the `guard`. The `guard` then paths to `report.location` and looks around until it finds `report.offender`.

If the `guard` doesn't find `report.offender` within x amount of time after `report.timeOfOccurrence`, the `guard` gives up and goes back to his post. The report remains, but the guard no longer actively searches for `report.offender`.

When the `guard` finds `report.offender`, they chase him down and get back `report.stolenItems`, incarcerate `report.offender` based on the value of `report.stolenItems`, and go back to `report.victim` and give them back `report.stolenItems`. The `report` is then disposed of.

This of course is a very old-fashioned representation of law enforcement. In a more modern setting, a `citizen` could call in a `report` to a dispatch center who would then relay the `report` to a nearby `guard`.

In summary, I like to create classes that store information and exchange those class instances between scripts. Think of how packets of data are sent through the internet. The machines that send them might be different, but they can understand the data inside the packets, so communication is possible.

# Answer
> 0 votes
## I would use *triggers* instead.

Imagine each guard has a circle or sphere collider spanning the size of this guard's detection area.

When a thief picks a pocket you turn on a collider on that thief object.

Both colliders are of course marked as triggers.

Now all you have to do is handle the OnTriggerEnter event in the guardian code.

# Answer
> 0 votes
I would do what lilotop suggested. Collision sphere is inexpensive, easy to visualize, and can be placed with an offset from the guard's head to mimic the difference in detection range based on the guard's facing direction. But if you have a good reason not to use any collision triggers, I would create one logical object (as opposed to a full game object) that all thieves register themselves to. When a thief steals, it raises a self-decaying flag in the registry, and the guards periodically check that registry and perform some filtering and prioritization (distance, LoS, time, etc) to decide whether they should go after the thief.

# Answer
> 0 votes
Achieving efficiency will vary by situation.

As lilotop mentioned, for purely radius-based or location-based checks, a collision filter with a detector and colliders can work well. Depending on the particulars of the physics engine in play, it may be more efficient to write a separate spatial query system. It may also be more efficient to invert the relationship, e.g. make the units like police have a large spherical shape and the events are then one-off collision queries into the spatial system.

If simple distance or area checks are invalid, a publish-subscribe (aka subscriber-observer) pattern may be best. In such a case, any agent that can see another agent would register itself as a visible observer, possibly with some filter flags. Events generated by an agent would then be forwarded to all registered observers.

An alternative to pubsub would be a combination of the spatial broadcasts and even filtering with vision checks. e.g., the guard within radius would get the crime event, but then might ignore it because a raycast form the guard to the perp fails. Whether this is more efficient will depend on the amount of caching and whether the vision tests are used for other systems. One might also broadcast the event in an area to find all *possibly* interested parties, then do vision tests to find out which ones could actually see the event, then register those that pass as subscribers for later events.

The simple most efficient solution if you have a low number of events and a high number of event chaser is likely to just use some kind of global-ish flag or list. When an event happens, push it into the list of flagged events. Officers would then scan this list of event on every tick, find the one that's closest that they care about, and select that as the active event of interest. This approach can also be combined with a spatial system if there's more than a handful of active events at any given time.

Yet another approach can involve generating flow fields or maps that guides AI. For instance, a crime might generate a flow map pushing all nearby law-enforcement units towards itself and civilian units away. The local pathing engine would use those overlays for moving units as appropriate, causing police is converge on the perp and civvies to run away.

A real game is probably going to use a large combination of many systems. There is no single fancy mega pattern that solves every use case efficiently.

# Answer
> 0 votes
Should other object access it when spawned with GetAllObjectOfClass(StateCheckingObject)?
**=\> No, you should have a list containing all StateCheckingObject in the beginning. Like this**

```
List<StateCheckingObject> m_AllActors;

```

That could be a heavy task for system since iterating over all level objects is not very efficient.
**=\> You are right, for more optimization, you can cache all possible combination of object sets there is. Like,**

```
List<StateCheckingObject> m_AllActors;
List<StateCheckingObject> m_AllPoliceActors;
List<StateCheckingObject> m_AllCitizenActors;
List<StateCheckingObject> m_AllRobberActors;
List<StateCheckingObject> m_FemaleRobberActors;
List<StateCheckingObject> m_MaleRobberActors;

```

It is not readability optimized, but it helps if you are having performance problem.

---
Tags: architecture, design-patterns
---


# Question
Title: How do I get diagonal 3d movement when two buttons are pressed?
I have a model moving using root motion. Currently, it's moving in 4 directions; Forward, Backward, Right, and Left.

Now, I want to make the character move in 45 degrees. I made a chart to understand the axes. (link because I can't have anymore attatchments)

http:// orig15(.) deviantart(.)net /fa04/f/2016/354/8/3/unity\_movement\_chart\_by\_blueneonkid-das9e8a.png

(Remove the spaces and parenthesis (yeah, it's a bit Youtube 2009, but what can I do? I'm new here.)

The character has a running animation for every direction, including the diagonal directions. Here is my animator controller set up:

I started out with trying to move diagonally left, and tried out a few scripts.

***Script #1 (The simplest)***:

```
public class Zcontroller : MonoBehaviour {

 private Animator myAnimator;

 // Use this for initialization
 void Start () {
     myAnimator = GetComponent<Animator>();
 }

 // Update is called once per frame
 void Update () {
     myAnimator.SetFloat ("VSpeed", Input.GetAxis ("Vertical"));
     myAnimator.SetFloat ("HSpeed", Input.GetAxis ("Horizontal"));
     myAnimator.SetFloat ("DiagSpeed", Input.GetAxis ("Vertical") + Input.GetAxis ("Horizontal"));
  }
}

```

Note: Here, I tried combining the axes inputs.

***Script #2***:

```
 using UnityEngine;
 using System.Collections;

 public class Zcontroller : MonoBehaviour {

     private Animator myAnimator;

     // Use this for initialization
     void Start () {
         myAnimator = GetComponent<Animator>();
     }

     // Update is called once per frame
     void Update () {
         myAnimator.SetFloat ("VSpeed", Input.GetAxis ("Vertical"));
         myAnimator.SetFloat ("HSpeed", Input.GetAxis ("Horizontal"));

         if (Input.GetAxis ("Vertical") || Input.GetAxis ("Horizontal")) {

             if ((Input.GetAxis ("Vertical") < 0f) && (Input.GetAxis ("Horizontal") > 0)) {
                 myAnimator.SetBool ("isDiagonalLeft", true);
             }

         } else {
             myAnimator.SetBool ("isDiagonalLeft", false);
         }
      }
  }

```

Here, I tried using a Boolean to trigger the animation

***Script #3:***

Results:

Script 1 did not work, and caused the character to move diagonally only when the Down Arrow key was pressed.

Script 2 also did not work, giving me the error: "Operator '||' cannot be applied to operands of type 'float' and 'float'."

Script 3 gave me some bracket errors.

What can I do to get the character to move diagonally properly?

Is there any way to combine two float values in code? If so, how?

EDIT: I tried a solution one guy on Unity Answers suggested, which was using a 2D Freeform Directional chart. Here's my setup for that (Link becaus I can't have any more attatchments):

http:// img04(.)deviantart(.)net/39b5/i/2016/354/9/b/zanimator\_setup\_2\_by\_blueneonkid-dasaome.png

(again, remove the spaces and parenthesis)

It still doesn't play the diagonal run animation whenever I hold two directional keys down.

I set the Diagonal Left animation to -1, 1 and the Diagonal Right animation to 1,1

(If anyone's wondering why I'm trying to achieve such an archaic way of movement, I'm trying to emulate the locomotion style of Megaman Legends 2, an Action RPG released in 2000 for the PS1.

Unlike modern Action RPGs where you can move 360 degrees, MML2 had 8 directions of movement. Kind of like Ocarina of Time.)

# Answer
I'm not sure I understand your question, but I believe you are trying to move the character based on it's animation state. I personally think that the reverse method is a better method: Animate the character based on it's movement.

Especially for a game like MegaMan Legends, this is the system that I would use.

1) Construct a direction vector based on the user's input. Something like:

```
Vector3 inputDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0 , Input.GetAxisRaw("Vertical"));

```

We leave the y component empty because y velocity is upward motion, which is typically added by pressing a button once (e.g. jump button), not holding a button.

2) Normalize the vector.

```
Vector3 velocity = inputDirection.normalized;

```

Since a diagonal input would result in a vector of (+/-1, 0, +/-1) which has a magnitude of ~ 1.41, we normalize the vector to avoid diagonal movement being faster than cardinal movement.

3) Apply your character's speed factor.

```
velocity *= characterSpeed;

```

This allows you to control how fast the character runs.

4) Get jump inputs.

```
if(Input.GetButtonDown("Jump") && isGrounded) velocity += (0, jumpStrength, 0);

```

Here we add jump inputs. We use GetButtonDown and isGrounded to avoid double jumps, and you can tune the strength of the jump by changing jumpStrength. We don't normalize this vector because, true to MegaMan's design, you maintain your horizontal velocity when jumping.

6) Apply the movement to your character.

```
transform.Translate(velocity);

```

You can use a physics method here if you choose, but I find this much simpler. If you need to worry about collisions, you can use velocity to perform a RayCast to see if you will be overlapping an object after translating. If so, only translate as far as you can.

7) Send your velocity variables to mecanim.

```
myAnimator.setFloat("xVelocity", velocity.x);
myAnimator.setFloat("yVelocity", velocity.y);
myAnimator.setFloat("zVelocity", velocity.z);

```

You will use these variables to switch between your animations. You will of course need to create these variables in mecanim as well.

8) Set up your blend tree in mecanim.

You can use a Blend tree to blend your 8 animations while using the velocity variables to control the blend direction/amount. I personally would have used just 4 animations for each cardinal direction and blended between them for the diagonal directions, but if your animations are all unique in some way then it would of course be necessary to have all 8 of them.

This is the system I have used in all of my projects thus far, and it has always served me well. I hope you find this helpful.
> 1 votes

---
Tags: unity, c#, movement, character, boolean
---


title: Where did I lose vertex binding?

text:
# Question
Title: Where did I lose vertex binding?
I make OpenGL render framework for my bachelor graduate work. I created simple Model and Shader classes. But when I tried to render some vertices, they do not render. I saw with an OpenGL profiler, that I haven't vertex data, but in code I bind it.

There's my main class:
```
GLfloat vertex_positions[] = {
        0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
        0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
        -0.5f, -0.5f, 0.0f, 0.0f, 1.0f
};
GLchar *vertexShader = (GLchar *)
                "#version 150\n"
                "\n"
                "in vec2 position;\n"
                "\n"
                "void main()\n"
                "{\n"
                "    gl_Position = vec4(position, 0.0, 1.0);\n"
                "}";
GLchar *fragmentShader = (GLchar *)
        "#version 400 core\n"
        "\n"
        "out vec4 fColor;\n"
        "\n"
        "void main()\n"
        "{\n"
        "    fColor = vec4(0.5, 0.4, 0.8, 1.0);\n"
        "}";
static const GLfloat vertex_colors[] =
        {
                1.0f, 1.0f, 1.0f, 1.0f,
                1.0f, 1.0f, 0.0f, 1.0f,
                1.0f, 0.0f, 1.0f, 1.0f,
                0.0f, 1.0f, 1.0f, 1.0f
        };
Shader shader;
shader.CompileShader(Shader::ShaderType::Fragment, fragmentShader);
shader.CompileShader(Shader::ShaderType::Vertex, vertexShader);
glBindFragDataLocation(*shader.GetProgram(), 0, "fColor");
shader.Link();
Texture texture((GLfloat *) vertex_colors, 16);
Model model (vertex_positions, &shader, &texture);
while (!glfwWindowShouldClose(window))
{
    static const float black[] = { 0.2f, 0.3f, 1.0f, 1.0f };
    glClearBufferfv(GL_COLOR, 0, black);
    shader.Bind();
    model.Draw();
    glfwPollEvents();
    glfwSwapBuffers(window);
}

```

And my model class:

```
void Model::Draw() {
glBindVertexArray(_vao);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glDrawArrays(GL_TRIANGLES, 0, 3);
}

Model::Model(GLfloat meshVert[], int m_size, GLuint vertexInd[], int
v_size, Shader *material, Texture *texture) {
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);

glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*m_size, meshVert,
   GL_STATIC_DRAW);

GLint posAttrib = glGetAttribLocation(*material->GetProgram(), "position");
glEnableVertexAttribArray((GLuint) posAttrib);
glVertexAttribPointer((GLuint) posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);

GLint colAttrib = glGetAttribLocation(*material->GetProgram(), "color");
glEnableVertexAttribArray((GLuint) colAttrib);
glVertexAttribPointer((GLuint) colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

}

```

P.S.: OpenGL profiler breaks on command `glDrawArrays`, but when I saw data info, it was empty. That's why I think I lost some data bind.

P.S.S: System: macOS Sierra, Intel HD 6000.

# Answer
> 1 votes
Your polygon is wound clock-wise which by default will get culled if `GL_CULL_FACE` is enabled.

Try calling `glDisable(GL_CULL_FACE);` to disable face culling, it should be disabled by default but it might not be the case due to glfw.

Also try calling `glDisable(GL_DEPTH_TEST)` before rendering as well.

And your model class instantiation does not match your class constructor:

```
Model model (vertex_positions, &shader, &texture);
Model::Model(GLfloat meshVert[], int m_size, GLuint vertexInd[], int v_size, Shader *material, Texture *texture)

```

# Answer
> 1 votes
In your call to `glDrawArrays()` you're telling it to only draw a single triangle (3 vertices). The last parameter, `count` is the number of indices to draw. From the man page:

> *count*
>
> Specifies the number of indices to be rendered.

Unless you're only drawing a single triangle, you probably need to give it a larger number.

# Answer
> 0 votes
Your shader doesn't use color attribute, but you are trying to use it in C++ code.

Comment out these lines:

```
GLint colAttrib = glGetAttribLocation(*material->GetProgram(), "color");
glEnableVertexAttribArray((GLuint) colAttrib);
glVertexAttribPointer((GLuint) colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));

```

---
Tags: opengl
---


# Question
Title: Hinge joint rope breaks away when connected platform moves
I use hinge joint 2D components to create my rope, and a distance joint to connect it to a moving platform.

On the moving platform I have a distance joint that connects to the first chain joint, so that allows the platform to move, and the rope should follow it.

The problem is that when I move the platform the joint connection will break and joints go crazy. Is there any solution for that?

When I move the circle, all the joints go crazy:

# Answer
The problem was I was moving the platform by its transform, not a rigidbody.

Instead, I found I should use `rigidbody.velocity = dir` or just `rigidbody.addForce(dir)`

Make sure that max force and max torque are set to infinity for each hinge joint - I'm not sure if this is needed for a distance joint.
> 1 votes

# Answer
To me it looks like you're using way too many joints for it to work smoothly.

## Anyway, to solve the joint breaking problem...

Take a look at their properties, there's a *max force* and a *max torque* value you can set to *infinity* so it will never break.

Again, this might help with the problem you described, but I'm afraid this might be the wrong direction for most rope animations.
> 0 votes

---
Tags: unity, 2d, joints, rope-physics
---


title: Designing an RPG damage type system

text:
# Question
Title: Designing an RPG damage type system
I made this thread to gather what the majority of RPG players like in terms of damage variety in a hack-and-slash game. I play quite a bit of ARPG (mostly Diablo 3 and Grim Dawn as of now) and recently have generated some game ideas of my own.

One specific criteria that I am reaching is **intuitiveness**. The players should be able to easily distinguish between the damage types and choose the correct way to build their character suiting to their flavors.

At the moment, I am stuck with deciding the right number of **damage types** and what they are. I have a basic list for myself:

Physical

Magical

Fire

Ice/Cold

Lightning

Poison

Here comes another question: should **Magical** be there? Is it a redundancy since the 4 elemental Fire,Cold,Lightning and Poison is "magical" already? or Should there be an independent and unique type called Magical? Or, should the Magical damage, if increased, will also modify all those elemental damage? I am looking for a good desgin here.

Next question, I want to implement the mechanics of **Bleeding** as a Damage Over Time type of damage. Then, what type of damage should Bleeding be? Physical? or Poison? I have a solution, which is: for each damage type, add a "Duration" counterpart which represents the DOT of this damage type, then the list becomes:

(Type,Duration damage of this type)

Physical, Bleeding

Magical, Corruption(just a random word to fill in)

Fire, Burn

Cold, Chill

Lightning, Electrified

Poison..........???

Here comes the problem, Poison is already a DOT, introducing another DOT counterpart for Poison would be weird. Another problem with this system is that it is complicated, so many stats. So my question is, how do we efficiently implement the least amount of damage type to produce the most amount of diversity in gamestyles and build types. I really want to promote freedom and creativity, which means that if someone likes playing DOT lightning he could.

Sorry if my questions aren't clear, but I would love if everyone shares their ideas of a Damage type system, how many are there is good, and how does damage over time works.

# Answer
> 5 votes
I'll get to some specifics about what you're asking, but first I want to offer some friendly advice: if you don't know the answers to simple questions like this then you shouldn't be considering an online-multiplayer RPG as a project. What you're talking about is RPG game systems 101 and it goes all the way from basic pen & paper systems to complex MMORPGs.

Frankly, you're not ready if you don't already know the fundamentals inside and out. I would strongly suggest you spend some time as a GM/DM for a pen & paper group and learn a number of big systems (D&D, 5 Rings, White Wolf, etc) until you understand not only *how* they are different but *why*.

To give you some help here are a few thoughts:

1) You're focusing too much on specifics and not enough on the underlying design principles. It doesn't matter if you have a damage type called "Magical" because that's just a descriptive name, what matters is how it's implemented and what differentiates it from other damage types.

For example, what makes Ice different from Lightning? In most systems it's that ice has some form of cold/chill/freeze effect and lightning has some form of shock/stun/chain effect. Those characteristics are then what guide you to design the skills/spells/auras/etc that use those elements. An ice spell could shatter and slow enemies, a lightning spell could shock and interrupt attacks, a poison spell could cause confusion and lead to less accurate attacks, etc. It's whatever YOU decide.

2) Don't confuse damage effects and damage types. The former is how damage is applied (up front, over time, after a delay, etc) and the latter is what kind of damage is applied. When you look at most RPG systems a "Bleed" is typically a damage effect (DoT) and so also needs to be given a damage type (Physical).

Poison is a bit different because some games use it as both, but I would strongly suggest that you refrain from doing that. It's confusing and ultimately doesn't *gain* you anything, so I would choose one or the other and design around that decision.

3) Having a "base" damage category (Physical, Magic, etc) is fine from a design perspective, but I would advise you to NOT allow attacks/weapons/stats to directly impact or use the base category if you go that route because it will create an absolutely nightmare for damage/mitigation balance.

Let's say you have a "Magic" category containing 4 damage types (Magic, Ice, Fire, Chaos). If you allow a weapon to do "Magic" damage then it will either be garbage or overpowered depending on whether elemental damage and resistances "double-dip" or not. Here are a few potential pitfalls:

* How is mitigation determined for both elemental and base magic damage?
* Do you derive magic resistance from base stats, from item stats, or both?
* Does magic resist also effect elemental resist and if so is it additive, multiplicative or added separately? If separately is it mitigated first and how does that impact the second calculation?
* How is damage increased and is it handled the same way as resists? (All the same questions apply)

For example, look at Diablo 3's resistance system where you have "all resist" and individual resistances. Ask yourself: what is the purpose of individual resistances in D3 and are they effective? The answer is no, they are completely pointless because they are completely outclassed by all resist in every way.

Why? Here are a few reasons:

* The resistances aren't even remotely balanced, physical is far better than the elemental resists.
* You can gem for All Resist but not for individual resists.
* You can't gain adequate resists across the board with individual resists.
* The play-style of the game relies on avoiding damage more than mitigating it.

I could continue, but the point is that individual resists don't serve any practical purpose in the game. Just like the other pointless secondary stats like chance to fear on hit, and basically every gem that isn't main-stat or all resist. D3 does a lot right, it's gem and mitigation system are two things that aren't done well at all.

This is getting long so I'll wrap this up by offering a couple suggestions:

1) Design your classes or builds around the type of play-style you want to enable and not the type of damage they do. Once you've figured out those then it's a lot easier to figure out the damage types.

2) When creating your damage types: KEEP IT SIMPLE. You don't need to allow for every single possible combination, frankly games that try to do that inevitably fail... either because the systems don't work, are extremely boring because everything is homogenized, or because they offer the illusion of choice but have no actual substance.

3) Stick to the classics. Having both non-magic and magic damage types are important, but make sure they are relatively even in power when compared with how hard/easy it is to mitigate those damage sources. Also, make sure each damage type has a clearly defined purpose or play-style, don't add things just for the sake of variety. You're better off sticking with fire, ice, lightning and making them *unique* than adding water, air, earth, dark, light, holy, chaos, poison... and having them all be clones.

Good luck :P

# Answer
> 3 votes
I think you're going about this from the wrong end. Damage types are tools in your toolkit to help you achieve a goal, **they are not a goal in and of themselves**.

If you look at damage types, they have various different aspects:

* Let a player deal better with groups of enemies, but comparatively weak against a single enemy
* Do a lot of damage up front, then fall off (good in short battles against weaker enemies)
* Do little damage that adds up over time (good against strong enemies that you'll spend a while fighting)
* Bypass armor or shields.
* Do little damage, but allow delaying or moving enemies (good for clearing enemies away from objectives or keeping that heavy hitter off you while you dispatch of her minions).
* Combine with other damage types so that if you trigger several at once, you suddenly deal a lot of damage.
* Remove the effects of all other weapons when triggered.
* Output no more damage than all other damage types the player has available right now, but by virtue of being a different type, immunities some enemies have against all the other damage types do not apply to them.

### Why do we do that?

Well, the game would be very boring if it was just about generating enough damage in a short amount of time to kill the enemy. This is good for early enemies, where the player is still learning the game. Later on, you want to give the player some new mechanics to figure out before they can get bored.

Like giving enemies shields, and a few damage types that can bypass or damage shields. You're basically giving your player a bag full or building blocks and telling them to build a house (i.e. defeat the enemy), and the interesting part about the game becomes figuring out which bricks to assemble in what order to achieve the desired result. Some pieces are very useful but also very rare (i.e. have a long cooldown), so the player has to approximate that one using other pieces when she's already used the one she had.

### As an Example

In Star Trek Online torpedoes do not penetrate shields, but do a lot of damage. Phaser beams mostly damage shields, but don't do that much damage to the actual ship even once the shields are down. So while you'd at first go for the damage type that does the most damage, you'll notice that won't damage shielded ships. So you need to figure out to first use your beams to take down the shields, then send a torpedo after it to finish it off before its shields can repair.

### Keep the Curve in Mind

So try thinking of damage types as abilities that grow in complexity to match the increasing complexity of enemies. You want a soft curve so your players have a chance to learn the basics at first. That they are magic or lightning or ice is really just set dressing.

You often first come up with a power that needs to fit certain requirements (e.g. allow me to fight the big boss at the end of the level, who is a damage sponge and needs to be stronger than all previous bosses you've already won against, but without giving players a power that is so strong it will make all other enemies no longer challenging), and then try to come up with a name and appearance that fits your world, your story and design aesthetic. Or that makes a certain battle that's pivotal to the story feel more epic than all others before or after, but doesn't break the game by making you too strong.

### Coming up with a damage type

Lightning in ArcheAge probably just started as "I need a power that looks cool and deals with several enemies, but is limited in number of enemies so first-level sorcerers don't clear out that level 10 area over there too early".

On the other hand, games like STO that have a TV series to draw from sometimes see an ability on the show and then try to make it fit in the game mechanics. That may happen by massaging a new enemy's abilities to fit the kind of damage you'd expect a certain weapon to dish out, or by picking a damage type from the ones they *can* use right now that is close enough to how the weapon's in the show looks.

# Answer
> 0 votes
I think that you should have two main types of damage; Physical and Magical. Then split those main categories into subcategories: Physical could have subcategories blunt, puncture, and slash, while Magical could have your elements of choice such as Ice, Fire, or Electricity.

For each damage type, you could have a DoT effect or you can just have generic status effects that can be applied based on what you're using: things like Stun, Root, Concussed, Disarmed, etc could be status effects for physical damage types, and for your magical damage types you could have the typical On Fire, Frozen, Shocked, etc. Some of these could be damaging and some could just be plain crowd control (or both), but the main thing is that each needs to be unique in its effect so that you have meaningful choices when it comes to which effect you want to apply. I think that the presence of meaningful choices, opportunity costs, and trade-offs are what role-playing games are all about.

---
Tags: game-design, rpg
---