Input float not switching to zero

I’m using acceleration to move my player, and to decelerate the player when switching directions I’m relying on the input switching to zero for a brief moment before switching to the opposite value.

But when you let go of one input at the exact same time that you press another one down, it does not reach zero. Instead, it just switches values.

Is there a way to prevent this from happening ?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour
{
    public float speed = 0f;
    public float maxSpeed = 350f;
    Rigidbody2D rb;
    private float accelSpeed = 750f;
    private float mover;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        mover = Input.GetAxisRaw("Horizontal");

        if (mover != 0f && speed < maxSpeed)
        {
            speed += Time.deltaTime * accelSpeed;
        }
        if (mover == 0)
        {
            speed = 0f;
        }

    }
    void FixedUpdate()
    {
        rb.velocity = new Vector2(speed * mover * Time.deltaTime, rb.velocity.y);
    }
}

There is no guarantee that you will see the Horizontal axis equal to zero when switching sides. Also, it looks like you don’t actually decelerate when turning around, since you set the speed to 0.

If you want to actually decelerate and then accelerate in the opposite direction, I suggest something like this:

float targetSpeed = 0f;
float currentSpeed = 0f;
void Update()
{
    mover = Input.GetAxisRaw("Horizontal");
    targetSpeed = mover * maxSpeed;
}

void FixedUpdate()
{
    currentSpeed = Mathf.MoveTowards(currentSpeed, targetSpeed, Time.fixedDeltaTime * accellSpeed);
    rb.velocity = new Vector2(currentSpeed, rb.velocity.y);
}

Mathf.MoveTowards will start at the first parameter and move it towards the second parameter (either increase or decrease) with a maximum step size defined by the third parameter.

thanks so much, This works great. That solves all the issues I was having. I really appreciate it!!