So I'm in the early stages of making an FPS game and I've just implemented a sprint and crouch function (crouch only slows the player down at the moment). the functions are simply this:
private void sprintInput()
{
if (Input.GetKeyDown(sprintKey))
{
movementSpeed *= 2f;
}
if (Input.GetKeyUp(sprintKey))
{
movementSpeed /= 2f;
}
}
private void crouchInput()
{
if (Input.GetKeyDown(crouchKey))
{
movementSpeed /= 2f;
}
if (Input.GetKeyUp(crouchKey))
{
movementSpeed *= 2f;
}
}
However written like this, they can obviously be activated both at the same time. But I want crouch to overwrite sprint. So if I use sprint and crouch at the same time, only crouch is activated. I've tried multiple methods but nothing works, I'm sure that I'm missing something painfully obvious, I just don't know what.
Set a boolean variable to true/false when crouching or not.
bool isCrouching;
private void crouchInput()
{
if (Input.GetKeyDown(crouchKey))
{
isCrouching = true;
movementSpeed /= 2f;
}
if (Input.GetKeyUp(crouchKey))
{
isCrouching = false;
movementSpeed *= 2f;
}
}
You can then use that variable to make sure you're not crouching before sprinting:
private void sprintInput()
{
if (!isCrouching && Input.GetKeyDown(sprintKey))
{
movementSpeed *= 2f;
}
if (!isCrouching && Input.GetKeyUp(sprintKey))
{
movementSpeed /= 2f;
}
}
The sprinting modifier will only be available to be activated whenever the crouching var/button isn't in use.