Why am i getting this error when i use clamp()?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By X

Error: Invalid type in built-in function 'clamp'. Cannot convert argument 1 from Nil to float.
Godot: 3.2.3.stable

Hi. I want to clamp the max value of the HP of my character, so when something restore his life, it does not go over it’s max value.

I know that i can do something like this:
HP -= Damage #(What is a negative value) if HP >= MaxHP: HP = MaxHP
But i wanna something more simple and clean.

:bust_in_silhouette: Reply From: jgodfrey

Hard to say much more than what the error already says without seeing the code. The first argument you’re passing to clamp is null. There are some usage examples in the docs, but it’s pretty straight forward…

Related, if you’re only interested in clamping to some maximum value (instead of clamping within a range), you can use the min and max functions. For your case, something like this would work…

HP = min(HP, maxHP)

That’ll return the lesser of the 2 values passed in - which will effectively cap the maximum value to the smaller of the 2 values.

jgodfrey | 2020-11-20 00:59

Thanks you.
I was using wrong the clamp() method.

For anyone with this same question, my code is something like this:

export var MaxHP = 5
onready var TheHP = MaxHP
onready var HP = clamp(TheHP, 0, MaxHP)

func Damage(DP):
	TheHP -= DP
	HP = clamp(TheHP, 0, MaxHP)
	TheHP = HP
	
	if HP <= 0:
		dead()

I don’t know if is the optimums way, but it’s works!

X | 2020-11-20 20:56