Created
July 22, 2022 21:07
-
-
Save khadzhynov/23e37e931a4456fef503a8b1e15bf890 to your computer and use it in GitHub Desktop.
Unity C# Fibbonachi LevelUp Xp progress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
namespace GG.Utils | |
{ | |
[Serializable] | |
public class FibbonachiXp | |
{ | |
//just useful value (approx) | |
public const float FIBBONACHI_MULTIPLIER = 1.618f; | |
public event Action<int> OnLevelUp; | |
public event Action<int> OnXpChanged; | |
[field: SerializeField] | |
public int Level { get; private set; } | |
public int NextLevelUpTarget => CurrentStepSize + AllPassedStepsSum; | |
[field: SerializeField] | |
public int PreviousStepSize { get; private set; } | |
[field: SerializeField] | |
public int CurrentStepSize { get; private set; } | |
[field: SerializeField] | |
public int AllPassedStepsSum { get; private set; } | |
public int LeftForLevelUp => CurrentStepSize - PassedForLevelUp; | |
public int PassedForLevelUp => TotalXp - AllPassedStepsSum; | |
[field: SerializeField] | |
public int TotalXp { get; private set; } | |
public FibbonachiXp(int firstStepSize) | |
{ | |
Level = 1; | |
TotalXp = 0; | |
AllPassedStepsSum = 0; | |
CurrentStepSize = firstStepSize; | |
PreviousStepSize = firstStepSize / 2; | |
OnXpChanged?.Invoke(TotalXp); | |
} | |
/// <summary> | |
/// Increment Xp | |
/// </summary> | |
/// <param name="xp">amount to increment on</param> | |
/// <returns>amount of levelups</returns> | |
public int AddXp(int xp) | |
{ | |
TotalXp += xp; | |
int levelups = 0; | |
OnXpChanged?.Invoke(TotalXp); | |
while (TotalXp >= NextLevelUpTarget) | |
{ | |
LevelUp(); | |
levelups++; | |
} | |
return levelups; | |
} | |
private void LevelUp() | |
{ | |
AllPassedStepsSum += CurrentStepSize; | |
int newXp = CurrentStepSize + PreviousStepSize; | |
PreviousStepSize = CurrentStepSize; | |
CurrentStepSize = newXp; | |
Level++; | |
OnLevelUp?.Invoke(Level); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment