# Measuring time?

I want to make a super mario bros. style jump, where the longer the button is held, the higher the player moves. How can I measure the amount of time that a button is held down?

I think the best approach would be to just keep jumping, up to a maximum height, while the button is held down. No need to record how long the button was held.

That said, to answer your actual question I believe you could just use GetKeyDown and GetKeyUp to record the time a button is held.

ie.

``````private float _timeDown = 0.0f;
private bool _isDown = false;

public class Jump : MonoBehaviour {
void update()
{
if (Input.GetKeyDown (KeyCode.Space))
_isDown = true;
else if (Input.GetKeyUp (KeyCode.Space))
_isDown = false;

if (_isDown)
_timeDown += Time.deltaTime;
}
}

``````

Obviosuly you'll want to reset _isDown sometime or whatever.

If you simply calculate the time the button is pressed to determine the jump height, you won't be able to start the jump until after the button is done being pressed. This is (probably) not the behavior you want.

Perhaps what you should do is have a value for your jump speed, and then a max jump height. Then while the button is pressed, have the player jump for as long as they haven't reached the max jump height.

variables:

``````private float jumpSpeed = 2.0f;
private float maxJumpHeight = 10.0f;
private float currentJumpHeight = 0.0f;
private bool canJump;

``````

and then wherever your update function is where you're handling the jumping...

``````float yMovementModifier = 0.0f;
if (canJump)
{
if (Input.GetKey(KeyCode.Space))
{
//if our jump hasn't hit the max jump height yet...
if (currentJumpHeight < (maxJumpHeight - (jumpSpeed * Time.deltaTime)))
{
//add our jumpspeed to our current jump height
currentJumpHeight += jumpSpeed * Time.deltaTime;
yMovementModifier = jumpSpeed * Time.deltaTime;

}
else
{
//we're at max height, so only allow the last bit of jump
currentJumpHeight = maxJumpHeight;
yMovementModifier = maxJumpHeight - (jumpSpeed * Time.deltaTime);

//also, since we're at max jump height, set a flag saying we can't jump anymore
canJump = false;
}
}
}
else
{
//your code here should check when the player hits the ground
//and then set the following flag:
canJump = true;
currentJumpHeight = 0.0f;
}