# Simple determining starting experience and to next lvl experience for RPG

I'm a very simple minded person and don't understand how algebraic functions translate into programming, but I'm trying to create a simple lvling system.

In previous threads I read equasions like "level = etc etc...", but instead what's happening is you're selecting the starting lvl of the character you create in an rpg database manager. What's needed then are startingExp and toNextLvl.

So what I've figured out so far (to do this in the simplest form) is:

int startingExp = 0;
for (int x = 0; x < selectedLvl; x++) {
startingExp += 100 * x;
}


Then:

int toNextLvl = startingExp + (selectedLvl * 100);


It's just a start, but I'm wondering if this is a valid way of going about it? I didn't want to use Math.Log as it takes and outputs doubles, and when people are posting their equasions I'm very confused as how I would translate y = (x ^ 2) into starting exp and starting toNextLvl exp...

• Does the code do what you want? Then I'd say ship it. :) Have you observed any specific problems with using this code? If so, we can help you solve those problems. But if it's just about whether the approach looks good, well, you're a better judge of the style of code you like maintaining in your codebase than we are. – DMGregory Apr 28 '18 at 13:34

The particular leveling formula you've written is equivalent to:

const int XP_INCREMENT_PER_LEVEL = 100;

int TotalXPToReachLevel(int level) {
return XP_INCREMENT_PER_LEVEL * level * (level + 1) / 2;
}


It's a quadratic, rather than exponential growth.

I got this using the formula for triangular numbers, the sum of the first n natural numbers, by noticing that your XP targets go up like this:

$$100 + 200 + 300 + 400 + ... +level \cdot 100 = 100 \cdot \left(1 + 2 + 3 + 4 + ... + level\right)$$

Doing this with your for loop is perfectly valid too, if you find that code clearer. You could probably do several thousand iterations through that tiny loop without seeing a meaningful performance impact in the kinds of scenarios where you need to calculate an XP target.

• That's what I was thinking, the for loop is called within a window in the Unity editor rather than in game. Thanks for the info, you've written it simpler and I think I'm starting to understand! – Mark Aven Apr 28 '18 at 23:16