Keyboard Input Issue with Run Toggle

I’m giving the player the ability to run by holding Shift while pressing the direction of travel, rather than walking which is without pressing shift. I have made the backpedal and sidestrafe movements slightly slower than the forward run when holding shift. My problem is this:
When I press S+Shift to backpedal the character moves at speed = 5 as intended. But if I then hold W as well, the backpedal speed increases to speed = 7, for that is the speed at which front run is set.

Here is what I currently have:

private void Running()
{
if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.LeftShift))
{
speed = 7;
}
else if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.LeftShift))
{
speed = 5;
}
else
{
speed = 3;
}

}

Thanks in advance!

You are seeing the issue because your first guard (if W & shift) fires even though you also press ‘S’.

I have two recommendations:

first, define what should happen if the user presses both W and S, and code for that.

Second, I recommend you make the code a Little more flexible, by nesting your tests: first test for ‘W’, then, after W was successful, test for shift;

if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.S) {
// trying to run both Forward and backwards. Result is Zero - or perhaps a very slow Forward
  speed = 0; // or 1
  return; // Exit to avoid lengthy else clauses
}

if (Input.GetKey(KeyCode.W)) {
  speed = 5;
  if (Input.GetKey(KeyCode.Leftshift) {
    speed = 7;
  }
  return; // avoid lengthy 'else'
}

... etc

Cheers,
-ch

I would rather write that if on this way:

if (Input.GetKey(KeyCode.W)) {
  speed = Input.GetKey(KeyCode.Leftshift) ? 7 : 5;
  return; // avoid lengthy 'else'
}

Ah, that’s more or less a “religious” question. I’m strongly opposed to syntactical shorthand (like ‘?’ or ‘+=’) that perhaps makes the code shorter, but definitely makes it more difficult to read, port, or maintain. All you achieve is to save a few keypresses once - when you write the line - at the permanent expense of readability and clarity. The end result (what the Compiler generates), however, is identical.

But as I said, it’s a matter of personal preference, taste and coding style.