Home > Back-end >  the value of speed won't change in my sprint toggle code
the value of speed won't change in my sprint toggle code

Time:01-08

I just got into developing using unity and I got the fps movement going, but I decided to test myself and tried to add a sprint toggle feature with my own code and it doesn't work, the issue is when I go into play mode and press left ctrl it doesn't change the value of speed, any suggestions would be appreciated.

if (speed == 5.0f && Input.GetButtonUp("LeftControl"))
    {
       speed  = 2f;
    } 

    if (speed == 7.0f && Input.GetButtonUp("LeftControl"))
    {
        speed -= 2f;
    }

CodePudding user response:

Never use == for floats due to floating point inaccuracies! See e.g. Is floating point math broken?

rather store a bool flag like

private bool isSprint;

and then do e.g.

if (Input.GetButtonUp("LeftControl")) 
{ 
    // toggle the flag
    isSprint = !isSprint;
    // ternary expression using the first value if "isSprint" is true 
    speed = isSprint ? 7f : 5f; 
}

Further instead of hardcoded values I would also expose those in the Inspector so you can edit them on the fly:

[SerializeField] float normalSpeed;
[SerializeField] float sprintSpeed;

and

if (Input.GetButtonUp("LeftControl")) 
{ 
    isSprint = !isSprint; 
    speed= isSprint ? sprintSpeed : normalSpeed; 
}
  • Related