Equation Help

I’m trying to figure out how I can determine a numbers percent position between two other numbers. For example, we all know that 5 is 50% of the way from 0 to 10. Likewise, 17 is 70% of the way between 10 and 20. I need to do this in code (and I’m sure I need an equation to figure this out). I have a GUI bar that shows how close the player is to leveling up. The bar fills as the player gains experience points. So if the player has 165 experience points, and needs 330 the bar would be half full. When the player gets to 330 experience points the bar is full and the player levels up. Now here’s where the problem comes in. The player now has 330 experience points, and needs 500…but the bar doesn’t drop back down to the starting position. I always need the bar to be positioned at a percentage point between how much experience the player needed for the last level up, compared to the next level up.

Level 1 - Starting EXP = 0 … Required EXP for Level Up = 100

So at level one the experience bar is at the 0 position, and as the player gains experience it goes up. Once the player has 100 experience it’s full.

Level 2 - Starting EXP = 100 … Required EXP for Level Up = 300

At level 2 the bar should be back at the 0 position. When the player goes from 100 to 150 the bar should be 25% full (since 150 is 25% of the way from 100 to 300).

Any ideas on what this equation should look like?

range = barMax - barMin
curLoc = experiencePoints - barMin;
percent = barMin / range;

In your Level 2 example:

range = 300 - 100 (so, 200)
curLoc = 150 - 100 (so, 50)
percent = 50 / 200 (so, 0.25)

Or, did I miss something?

Jeff

Mathf.Lerp(lowValue, highValue, yourValur);

You can also interpolate manually.

That LOOKS about right. Might have to make a few tweaks. Going to implement it and give it a go. Will let you know the results. Thanks! :slight_smile:

I ended up using the following equation if anybody else ever wants to simulate something like this.

Equation = (curValue - minValue) * (maxXPos - minXPos) / (maxVaue - minValue) + minXPos;
So In code it’d go something like this…

float EXPCachedY = EXPTransform.position.y;
float MaxXValue = EXPTransform.position.x;
float MinXValue = EXPTransform.position.x - EXPTransform.rect.width;
int lastRequiredEXP = 100;
int currentEXP = 150;
int nextRequiredEXP = 300;

float curEXPXVal = EXPTransform.position.x;
        float newEXPXVal = CalculateValue(currentEXP, lastRequiredEXP, nextRequiredEXP, MinXValue, MaxXValue);
        Vector3 curEXPPos = EXPTransform.position;
        Vector3 newEXPPos = new Vector3(newEXPXVal, EXPCachedY);
        if(newEXPXVal != curEXPXVal){
            EXPTransform.position = Vector3.Lerp(curEXPPos, newEXPPos, Time.deltaTime * 5f);
        }

private float CalculateValue(float curValue, float minValue, float maxVaue, float minXPos, float maxXPos){
        return (curValue - minValue) * (maxXPos - minXPos) / (maxVaue - minValue) + minXPos;
    }