Level system optimization

Hello everyone!
So recently, I was working on my own level system, it works fine, but I want to optimize it with single (or multiple) formula(s).
Here is the function to handle the level according to the exp.


local StarterEXP = 25 
local AddEXP = 25

local function CalculateLevel(exp)
	local level = 0
	while (exp or 0) >= AddEXP*level+StarterEXP do
		exp -= AddEXP*level+StarterEXP
		level += 1
	end
	return level
end

Ok so, each level you need to gain ax+b experience points to level up, where x is your current level. And so the formula to get the total (lifetime) xp needed to reach the next level is just the sum of the individual requirements of the levels.

So if the first level requires gaining 0*addExp + starterExp, and the next requires another 1*addExp*starterExp, etc, we need to sum all those to get the total xp needed. To get the sum of 1+2+3+4.. etc we can use the formula n(n+1)/2, also known as the formula for triangular numbers.

Edit: I forgot it starts at 0, so the triangular formula becomes n(n-1)/2. I fixed it.

This gives us
xp = n(n-1)a/2 +bn
where n is your current level and xp is the total experience needed to get that level. To get the level from the experience, we just need to solve this formula.

Working out the brackets, we see that we can simply apply the abc formula. Just blindly applying it gives us something like:

local function getLevel(exp)
	local det = math.sqrt(math.pow(starterExp - .5 * addExp, 2) + 2 * addExp * exp)
	local result = (.5 * addExp - starterExp + math.max(det, -det))/addExp
	return result
end

I guess we only need one side, giving us:

local function getLevel(exp)
	local det = math.sqrt(math.pow(starterExp - .5 * addExp, 2) + 2 * addExp * exp)
	return math.floor((.5 * addExp - starterExp + det)/addExp)
end

Hope you can follow all the steps, hope this helps!

Thanks a lot.
I am not really good when it comes to progressions and etc.
That helped a lot

1 Like