Search code examples
javascriptmathequationcomputation

Calculate XP percentage completed for multiple levels (similar to call of duty/etc)


I am developing an XP/Leveling system for a website. Think of it like Call of Duty levels.

For example

Level 1 = 0 - 100XP
Level 2 = 100 - 200XP
Level 3 = 200 - 300XP

Now obviously for level 1, since it's 100 level max, I can do

const currentXp = 50;
const nextLevel = 100;

function calculateProgress(currentXp ,nextLevel) {
  return (currentXp / nextLevel) * 100;
}

// returns 50% (which is correct), this means the progress bar would be halfway full. 

However, when you get past 100, this equation does not work anymore. For example,

  const currentXp = 150 
  const nextLevel = 200

function calculateProgress(currentXp, nextLevel) {
  return (currentXp / nextLevel) * 100;
}

// returns 75%, and the progress bar is 75% full,  when it should be 50% full, because 150 is halfway in between 100 and 200 i.e 50% progress in between the levels. 
 

This is where thinking of call of duty comes into play. I am trying to calculate the progress between 2 levels. Not simply the percentage a particular number is of another number.

I have spent numerous hours trying to come up with a solution and have utterly failed.

Any insight/advice/help would be so very much appreciated. Thank you so much for your time.


Solution

  • you should use:

    ((currentXp - previousLevel) / (nextLevel - previousLevel)) * 100
    

    example:

    ((150 - 100) / (200 - 100)) * 100 = 50