¿How can i add until a specific value?

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

Sorry if i cant explain myself good in the title, but i do have a var called stamina, and it reduces when the player is running, until 0, but it can stop until any number beetween 0 and 100 if the player stops running, if the player stops running then a func called recharge adds 20 points to stamina until it hits 100 or more, the problem is that the stamina can add up to 119 if stopped running at 99 stamina, how can i put a maximum to the stamina adding? sorry for my bad english.

:bust_in_silhouette: Reply From: StopNot

How about just checking the stamina value?

const MAX_STAMINA = 100

func _recharge(stamina):
    #your code
    if stamina > MAX_STAMINA:
        stamina = MAX_STAMINA

I wanted to add another example since Wakatta had a brilliant idea to use clamp (see in the comments).

const MIN_STAMINA = 0
const MAX_STAMINA = 100

var stamina = 79

func _ready():

func _recharge(stamina_increase):
	stamina = clamp(stamina + stamina_increase, MIN_STAMINA, MAX_STAMINA)

This will give you the following output:


yes, thanks for the help

Arielrandal | 2021-06-23 18:05

Happy to help. Please vote my answer if that’s not too much trouble. :slight_smile:

StopNot | 2021-06-23 18:11

Another way to skin the cat is to use clamp

func _recharge(stamina):
    stamina = clamp(stamina, 0, 100)

0 being your minimum value
100 being your max

Wakatta | 2021-06-24 01:00

Excellent point. I don’t think I’d use a clamp for skinning cats though. :smiley:

StopNot | 2021-06-24 04:54