- Home /
CharacterController velocity
Hello, I'm trying to make my stamina value decrease as long as the charactercontroller is moving and the leftshift button is pressed. Should this code work? Because it doesn't.
var controller : CharacterController = GetComponent(CharacterController);
if(Input.GetKey(KeyCode.LeftShift && controller.velocity.magnitude > 0))
{
currentStamina -= Time.deltaTime;
}
Possibly if you change the > 0 to > 0.0 it might work. I have had similar problems in the past and I think that that is how I fixed it.
Are you using the $$anonymous$$ove or $$anonymous$$oveSimple function? CharacterController.velocity will only work if you use these functions, and will not work if you use transform.Translate.
Also, are you increasing the sta$$anonymous$$a anywhere? I would expect an 'else' in this context. $$anonymous$$aybe your increase is negating your decrease?
I sorted my issue somehow by changing the order of the if statement:
if(controller.velocity.magnitude > 0 && Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftShift))
{
currentSta$$anonymous$$a -= Time.deltaTime;
}
I see! Syntax always gets me! Thanks for clearing that up!
Answer by JoaquinRD · Aug 17, 2013 at 12:18 PM
This is a problem with the arrangement of your parentheses.
if(Input.GetKey(KeyCode.LeftShift && controller.velocity.magnitude > 0))
should have been:
if(Input.GetKey(KeyCode.LeftShift) && controller.velocity.magnitude > 0)