Acceleration in 2D

I’m working on a 2D platformer game and i’d like the player to be able accelerate, but my script doesn’t seem to be working. It just goes to max Speed instantly.
this is the script i made:
void Update()
{
dir = Input.GetAxisRaw(“Horizontal”);
}

    private void FixedUpdate() 
    {
        if (dir == 1 || dir == -1)
        {
            acceleration = TopSpeed - 0 / AccelerationTime;
        }
        Speed += acceleration + Time.deltaTime;
        if(Speed > TopSpeed)
        {
            Speed = TopSpeed;
        }
        velocity = new Vector2(Speed * dir * Time.deltaTime, 0f);

        rb.velocity = velocity;
    }

Any help would be appreciated.

acceleration = TopSpeed - 0 / AccelerationTime;


In this line, acceleration is always set to TopSpeed because zero divided by anything is 0. If you delete the 0 and the subtraction, you will get the behavior you want. Also, you should multiply acceleration by Time.deltaTime instead of adding if you want AccelerationTime to represent the time it takes to reach full speed.


acceleration = TopSpeed / AccelerationTime;

Speed += acceleration * Time.deltaTime;

As a challenge, see if you can redesign this using a coroutine. This will allow you reach top speed and stop accelerating, which means you won’t need lines 8-11.