# car deceleration is making my car reverse

I have a car that can accelerate and decelerate but the problem is when I’m not pressing ‘W’ the car is very slowly going backwards. I have the acceleration clamped so it shouldn’t have a negative value but it is. Please help.

using UnityEngine;
using System.Collections;

public class CarModelControl : MonoBehaviour {

float Acceleration;
float MinAcceleration = 0.0f;
public float MaxAcceleration = 30.0f;
public float AccelerationRate = 5.0f;
public float DecelerationRate = 10.0f;
public float rotateSpeed;
public float ReverseSpeed;

void Start () {

}

void Update () {
Acceleration = Mathf.Clamp(Acceleration, MinAcceleration, MaxAcceleration);
if (Input.GetKey(KeyCode.W))
{
Acceleration = Acceleration + (AccelerationRate * Time.deltaTime);
transform.Translate(Vector3.forward * Acceleration * Time.deltaTime);
Debug.Log(Acceleration);
}
else
{
Acceleration = Acceleration - (DecelerationRate * Time.deltaTime);
transform.Translate(Vector3.forward * Acceleration * Time.deltaTime);
}

if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.down * rotateSpeed * Time.deltaTime);
}

if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector3.back * ReverseSpeed * Time.deltaTime);
}

if (Input.GetKey(KeyCode.D))
{
transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime);
}

}
}

You are clamping the “Acceleration”, then modifying it, then using it (without clamping it again).

In order to clamp it effectively, you need to move the clamping so that it’s between the modification and the use.

if (Input.GetKey(KeyCode.W))
{
Acceleration = Acceleration + (AccelerationRate * Time.deltaTime);
Acceleration = Mathf.Clamp(Acceleration, MinAcceleration, MaxAcceleration);
transform.Translate(Vector3.forward * Acceleration * Time.deltaTime);
Debug.Log(Acceleration);
}
else
{
Acceleration = Acceleration - (DecelerationRate * Time.deltaTime);
Acceleration = Mathf.Clamp(Acceleration, MinAcceleration, MaxAcceleration);
transform.Translate(Vector3.forward * Acceleration * Time.deltaTime);
}

The reason the backward movement is so slow is that when decelerating, the line

Acceleration = Acceleration - (DecelerationRate * Time.deltaTime);

creates an ever-so-slightly negative “Acceleration”. This is then used, and then it’s clamped to zero at the start of the next Update(). So your clamping stops it from ever getting more than one frame’s worth of deceleration below zero, but you are letting it become negative and using it while it’s negative.

I have put “Acceleration” in quotes because the way you’re using that variable, it’s not an acceleration, it’s a speed.