← Pixel Dreamer Studio

Make HP and mana regen the same at any frame rate

Add the rate times delta to a float carry, move only the whole part into the stat, and keep the rest for the next frame.

Keep a float _carry, add per_second * delta to it every frame, move int(_carry) into the whole-number stat and subtract it from the carry. Converting each frame on its own throws the fraction away: in our Godot 4.7 test, value += int(40 * delta) regenerated 300 in 10 seconds at 30 FPS and 0 at 60, 144 and 240 FPS, where 400 was expected. The script gave 399 to 400 at all four.

The code

Put it on any node, or copy its _process into your character. Set per_second to a negative number to drain, for example while a spell is channeled. changed fires only when the number really changes, so a HUD bar does not have to redraw every frame.

extends Node
## Regenerates (or drains) a whole-number stat like HP or mana by per_second, the same at any frame rate.
## The fraction left over each frame is kept for the next one instead of being thrown away.

signal changed(value: int)

@export var value := 50
@export var max_value := 100
@export var per_second := 40.0  # negative drains, for example a channeled spell

var _carry := 0.0


func _process(delta: float) -> void:
	_carry += per_second * delta
	var whole := int(_carry)  # int() cuts toward zero, so a drain works the same way
	if whole == 0:
		return
	_carry -= whole
	var before := value
	value = clampi(value + whole, 0, max_value)
	if value != before:
		changed.emit(value)

What we measured

We called _process with a fixed delta for 10 seconds of game time at 30, 60, 144 and 240 FPS, at 40 per second, so the right answer is 400.

Why it happens

At 60 FPS, delta is about 0.0167, so 40 per second is 0.67 per frame. int() cuts that to 0 every frame, and roundi() turns it into 1, which is 60 per second. Either way the result depends on the frame rate, and on a fast screen the stat may not move at all. A float stat avoids the problem too, but HP and mana are usually whole numbers on screen and in save files.

What to change

Cooldowns have a frame and pause problem of their own: ability cooldown keeps counting while paused.

A whole spell system with mana: Spell Casting Kit for Godot 4 has cast, charge and channel spells with mana and cooldowns, aiming modes, elements and status effects.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Spell Casting Kit for Godot 4 is a whole spell system for Godot 4: cast, charge and channel spells with mana, cooldowns, aiming modes, elements and status effects.

More how-tos for Spell Casting Kit for Godot 4: Aim a spell at the mouse on a 3D floor · A cooldown that waits while the game is paused

More how-tos: Game systems