Making my car decelerate without driving backwards nonstop

Hello, I’m new at programming games, and i though i’d give it a shot.
I’m trying to make a car, and until now it slowly worked better and better, but now all i need is for it to decelerate. i tried to make it work, and it almost did, but it went reverse instead of just stopping, and when i tried to fix that it just couldn’t drive at all.

Is it possiple that any of you out there could help me with this? I’ve seen posts about it, but i have no idea half the codes they are using does.

(So far A and D keys are called testA and testD, cause i was testing it, to see if i could make it work)

my code:

public float movementSpeed;
public float movementAcceletarion;
public float maxMovementSpeedForward;
public float maxMovementSpeedBackward;
public float minMovementSpeed;

// Use this for initialization
void Start ()
{
    myRigidbody = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void FixedUpdate ()
{
    float horizontal = Input.GetAxis("Horizontal");
    bool testA = Input.GetKey(KeyCode.A);
    bool testD = Input.GetKey(KeyCode.D);

    HandleMovement(horizontal);

    if (testD == true) //accelration forward
    {
        movementSpeed = movementSpeed + movementAcceletarion;
    }//end

    if (testA == true) //acceleration backward
    {
        movementSpeed = movementSpeed - movementAcceletarion;
    }//end

    if (movementSpeed > maxMovementSpeedForward)//making sure u have a max speed forward
    {
        movementSpeed = maxMovementSpeedForward;
    }//end
    if (movementSpeed < maxMovementSpeedBackward)//making sure u have a max speed backward
    {
        movementSpeed = maxMovementSpeedBackward;
    }//end

}

private void HandleMovement(float horizontal)
{

    myRigidbody.velocity = new Vector2(movementSpeed, myRigidbody.velocity.y);

}

}

in the inspector - did you make sure to enter a negative value for maxMovementSpeedBackward ?

80159-drive.jpg

With these settings your code works just fine in my opinion.

okay, it might sound wierd, but i found the solution in a dream :stuck_out_tongue:

    if (testA == false & testD == false & movementSpeed > 0)
    {
        movementSpeed = movementSpeed - deceleration;
    }
   
   if (testA == false & testD == false & movementSpeed < 0)
    {
        movementSpeed = movementSpeed + deceleration;
    }