- Home /
The question is answered in comments, right answer was accepted
Check if a variable is true at the beginning of GetButton?
Hi guys! I'm creating a 2D platformer with a character who can walk, run, and jump. Currently the script below works fine, and the player is able to move at run speed when they hold left shift at any time. So, for example, the player can be walking, then jump and start holding shift in mid-air. This would make the character magically move at run speed in the air, which doesn't look very natural. The current script is an if statement in Update() that checks for GetButton; pretty simple.
void Update()
{
if (Input.GetButton("Run")) //left shift to run
{
speed = 10f;
}
else
{
speed = 5f;
}
}
What I'm trying to achieve is something that checks if the player is grounded (!isJumping) at the start of the GetButton (holding left shift), but lets them stay at run speed even if isJumping becomes true while they're holding the button. I've tried an if statement that checked if the player is grounded and holding the run button, but this stops the player from running whenever they're in the air because isJumping is true. I also tried putting a while loop inside that if statement that lets the player move at run speed while the button is held, but this just crashed Unity. :/ If anyone knows some way to achieve this or needs more clarification, please let me know! Thanks so much!
Can't you simply do:
void Update()
{
if (Input.GetButtonDown("Run") && !isJumping) //left shift to run
{
speed = 10f;
}
else if (Input.GetButtonUp("Run"))
{
speed = 5f;
}
}
...Yep, that worked. Thanks a ton! Sometimes I wonder how I don't think of these things on my own... I'm a bit of a newbie, so I just assumed that would stop the player from running in the air.