Search code examples
unity-game-enginelevelup

Formula for game levelup based on points


I know there is a simple answer to this - I just cant think of it. I'm developing a strategy game where scenery upgrades its levels based on points. So the result I'm looking for is this...

Level from points...

1 <= 1  
2 <= 2,3  
3 <= 4,5,6  
4 <= 7,8,9,10  
5 <= 11,12,13,14,15

you can see where this is going. So can anyone remind me of the simple formula to do this so I can go away and bow my head in shame?


Solution

  • The sequence you describe is a very known one, named triangular numbers sequence, that is defined by the formula:

    maxpt = (lv * (lv + 1)) / 2
    

    In your specific case, this formula gives the maximum of points maxpt you can have and still be at level lv.

    But you want the inverse of that. You want to know wich level lv you will be for a given number of points pt. This is named the triangular root of the number (as an analogy to the square root).

    You can directly invert the formula through the Bhaskara equation, but you'll need to do some tricks to correct the base index. That gives:

    lv = (int)((Math.sqrt(8 * (pt - 1) + 1) - 1) / 2) + 1
    

    That works for pt >= 1. For pt = 0 just return 0 to avoid a float point error (square root of a negative number).

    You can surely find more elegant solutions to this over the internet, though.