- Home /
MathF clamp not working
I have 2 variables I don't want them to go under 0.0 so I clamped them but when running the game they go under the minimum of the clamp, what have I done wrong?
 var health = 100.0;
 var hunger = 100.0;
 
 
 function Update () 
 {
     hunger = hunger - Time.deltaTime/4;
     
     if( hunger <= 5)
     {
         health -= Time.deltaTime/4;
     }
 }
 
 hunger = Mathf.Clamp(hunger, 0.0, 100.0);
 health = Mathf.Clamp(health, 0.0, 100.0);
Answer by Lovrenc · Nov 13, 2013 at 08:59 AM
Your "Mathf.Clamp" is not in Update function. In update you are lowering hunger every call, but your clamp is not called.
     var health = 100.0;
     var hunger = 100.0;
      
      
     function Update ()
     {
       hunger = hunger - Time.deltaTime/4;
      
       if( hunger <= 5)
       {
         health -= Time.deltaTime/4;
       }
       
 
       hunger = Mathf.Clamp(hunger, 0.0, 100.0);
       health = Mathf.Clamp(health, 0.0, 100.0);
     }
      
     
How come this doesnt throw syntax error? (or is this allowed in unityscript?)
It is allowed in Unityscript. I believe that everything that is declared outside of functions is run when the object is initialized.
Also you can have a better perfor$$anonymous$$g code by doing Time.deltaTime * 0.25 ins$$anonymous$$d of Time.deltaTime / 4. $$anonymous$$ultiplication is faster than division. ;) 
Your answer
 
 
             Follow this Question
Related Questions
Reading variable from other script 1 Answer
What is typed variable? 2 Answers
Distance in a Trajectory of a projectile 0 Answers
Unity3d Javascript Reference Script Variable 1 Answer
Walking Sound Script not working properly (JavaScript) 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                