So, my player’s stamina decreases when he runs, but it keeps decreasing in the negatives. I want it to stop decreasing at 0. Please help!
Here’s my script:
var maxStamina : float = 100;
var Stamina : float;
var minStam = 0;
//stamina
function Stam () {
//running
if(Input.GetKey("p")) {
Stamina -= .5;
}
if(Stamina == minStam) {
move.speed = 6;
}
if(Stamina > maxXP) {
Stamina = maxStamina;
}
}
rutter
August 21, 2014, 6:02pm
3
You’re looking for a clamp function. The Mathf class provides several:
Mathf.Min takes two values, and returns the smaller of the two
Mathf.Max takes two values, and returns the greater of the two
Mathf.Clamp takes one value and clamps it within a min/max range
You can find similar functions in many programming languages. You can write your own, too.
So, in your case, I’d try something like this:
Stamina = Mathf.Max(Stamina - 0.5, 0);
Or:
Stamina -= 0.5;
if (Stamina < 0) {
Stamina = 0;
//do something else in this block? (optional)
}
Or:
Stamina = Mathf.Clamp(Stamina, 0, maxStamina);
if(Input.GetKey(“p”) && Stamina > 0) {
Stamina -= .5;
}