← Pixel Dreamer Studio

Level up as many times as the XP covers

Loop while the XP is enough for the next level, and subtract what each level costs.

if xp >= needed levels up once per reward, however big the reward is. In our Godot 4.7 test, with 100 XP times the level needed for the next one, 1,000 XP at level 1 gave only level 2. Setting XP to 0 afterwards threw away 950 XP, and subtracting left the bar at 950/200. Use while and subtract the cost of each level: the same reward reached level 5 with 50/500 left over.

The code

Call add_xp() with every reward and put your own curve in xp_needed(). leveled_up fires once for each level gained, so you can play the level up effect for each one, or only for the last.

extends Node
## Add experience and level up as many times as it covers, keeping what is left over.
## Works for character levels, cultivation layers and skill ranks.

signal leveled_up(new_level: int)

@export var max_level := 99

var level := 1
var xp := 0


func xp_needed(lv: int) -> int:
	return 100 * lv  # your own curve goes here


func add_xp(amount: int) -> void:
	xp += amount
	# while, not if: one big reward can be worth several levels
	while level < max_level and xp >= xp_needed(level):
		xp -= xp_needed(level)
		level += 1
		leveled_up.emit(level)
	if level >= max_level:
		xp = 0

What we measured

Rewards of 50, 1,000, 30 and 5,000 XP from level 1, needing 100 × level XP for the next level. Two runs with the same results.

Why it happens

if only checks once, so a reward worth four levels gives one. The rest either disappears or piles up in the bar, and with subtract the player then catches up one level per later reward, at odd moments. while keeps going until what is left is less than the next level costs, which is what the player expects to see.

What to change

Breakthrough chances that fail too often in a row: pseudo-random chance. An effect for the moment it happens: level up effect that plays while paused.

A ready-made system: Xianxia Cultivation System for Godot 4 has realms, layers and breakthroughs with entry chances, tribulations, pills, spirit roots, techniques and save/load.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Xianxia Cultivation System for Godot 4 has realms, layers and breakthroughs with entry chances, tribulations, pills, spirit roots, techniques and save/load.

More how-tos: Game systems