Player movement change due to "if" statement?

I’m messing around with my player movement script and have noticed something which I cannot understand.

The original x-axis movement script (in FixedUpdate) I am using is:


        moveInput = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);

With this, the player moves around and stops immediately when the button is no longer being pressed down. However, if I move the second line into an “if” statement (shown below), the player slides around like he’s running on ice:


      moveInput = Input.GetAxisRaw("Horizontal");

    if (moveInput > 0.5 || moveInput < -0.5)
    {
        rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
    }

I’m curious why this is happening since both parts of the original script are intact, the only change that I can see is asking the perhaps redundant question of whether or not a button is being pressed down before letting the code run. I am very new to coding so I am expecting the answer to be something very simple, but I can’t find any results on google. Thanks.

@hypehog

This piece of code should work perfectly!

moveInput = Input.GetAxisRaw("Horizontal");
    if (moveInput > 0.5 || moveInput < -0.5){
        rb.velocity = new Vector2(moveInput * 1, rb.velocity.y);
    }else{
        rb.velocity = Vector2.zero;
    }

Explanation:

When you’re not pressing the key down, the variable “moveInput” has a default value of 0, which makes translates into this: rb.velocity = new Vector2(0, rb.velocity.y); making the object stop. But, when you use the if statement, the program never executes the previous statement, and that’s similar to pushing an object on a surface where there is no friction (neither with the surface nor the air) it will simply keep moving forward.