- Home /
Could anyone help me with a bit of math for an XP system?
If my required XP to level up is 95/100 and I award 10xp, what's the best way to check what's leftover and put it in a variable that I can add after I level up?
Because at the moment if 95/100 and award 10, it will level up and go to 0 losing out on the 5. Sorry if it's a bit of a vague/mundane question, I struggle with maths.
public float currentXP;
public float RequiredXP;
//If current is 95 and required is 100
public void GiveXp(float xp)
{
//check if the given xp is higher than the required xp
//And add the leftover into a variable so i can add on after
//To the levelup function
}
if I remember anything it may include the modulo % but I really struggle with math. Thanks
Answer by Divinitize1 · Sep 03, 2019 at 11:57 PM
I'll mark this as correct as it works, however, it might not be the best way of doing things, see the below post for a one-line solution that almost works.
public class xpSystem : MonoBehaviour
{
public float currentXP;
public float xpRequired = 100f;
public float totalXP;
public int level;
public GameObject xpBar;
public float xpOverflow;
void Update()
{
xpBar.GetComponent<UnityEngine.UI.Slider>().maxValue = xpRequired;
xpBar.GetComponent<UnityEngine.UI.Slider>().value = currentXP;
if(currentXP >= xpRequired)
{
LevelUp();
}
if(Input.GetKeyDown("space"))
{
GiveXp(15.7f);
}
}
public void GiveXp(float xp)
{
if(currentXP + xp > xpRequired)
{
xpOverflow = currentXP + xp - xpRequired;
Debug.Log("Leftover = " + xpOverflow);
currentXP += xp;
}
else
{
currentXP += xp;
}
}
void LevelUp()
{
level += 1;
xpRequired += 10;
currentXP = 0f;
currentXP += xpOverflow;
xpOverflow = 0f;
}
}
Answer by Cornelis-de-Jager · Sep 03, 2019 at 11:08 PM
Here is a oneliner that does that for you
public float currentXP;
public float RequiredXP;
public void GiveXp(float xp)
{
currentXP = currentXP + xp > RequiredXP ? (currentXP + xp) - RequiredXP : currentXP + xp;
}
Answer by BastianUrbach · Sep 04, 2019 at 06:54 AM
Are you sure you're not overcomplicating things by first setting it to zero and then adding the overflow again? I would just do it like this:
currentXP += xp; if (currentXP > RequiredXP) { currentXP -= RequiredXP; LevelUp(); }
Your answer
Follow this Question
Related Questions
xp math equation help 1 Answer
Problem with angles and rotations in a 2D top down space shooter 0 Answers
How can I get shader variable to map into a certain range? 0 Answers
Some math fun regarding scale and rotation 1 Answer
Calculating the perpendicular direction an AI ship needs to face to fire its cannons? 2 Answers