# How to make car accelerate/decelerate over time

So I’m attempting to make a realistic feeling car. I’ve got it running, turns feel alright, just how do I make it break appropriately, speed up appropriately, etc etc. I tried, not much luck, but it does stop for a second, go to 8 speed, then go to 30.

``````//inspector variables

var speed:float; //speed of the car, tweek as needed based on your scale
var turnSpeed:float; //turn speed
var timecar:float;
var accel: float;
function Update()
{
timecar += Time.deltaTime;
//grab the input axes
var steer=Input.GetAxis("Horizontal");
var gas=Input.GetAxis("Vertical");

//if they're hittin' the gas...
if (gas!=0)
{
//take the throttle level (with keyboard, generally +1 if up, -1 if down)
//  and multiply by speed and the timestep to get the distance moved this frame
var moveDist=gas*speed*Time.deltaTime;

//now the turn amount, similar drill, just turnSpeed instead of speed
//   we multiply in gas as well, which properly reverses the steering when going
//   backwards, and scales the turn amount with the speed
var turnAngle=steer * turnSpeed * Time.deltaTime * gas;

//now apply 'em, starting with the turn
transform.rotation.eulerAngles.y+=turnAngle;

//and now move forward by moveVect
transform.Translate(Vector3.forward*moveDist);
}
}
if (speed < 30){
speed++;
}
}
``````

I’ve never tried making a racing game in Unity, so I’m completely new to this. I do however have a good amount of experience I Unity as a whole. Thanks for helping!

Just a side-note, the Car Demo provided by Unity won’t work, and I didn’t want to use it anyways, I prefer making games from scratch.

Try making an acceleration var float. Like:

var accel : float = 1.0f;

then if(gas)
speed+= Input.GetAxis(“Vertical”) * accel;

Of course this isn’t formatted “code”, it’s
Just an example of something you could try…

Not sure what youre trying to accomplish but if
if (Input.GetKeyDown(“s”)) {
speed = 1;
while (speed < 16){
speed++;
timecar = 0;
}

is in an Update function…then if s is pressed speed will always be 16. (Because in 1 tick of update you are looping WHILE speed<16…so that loop will execute 15+ times in 1 update tick - forcing your speed to 16 right away.

You should just do:
private int maxSpeed=16;
if (Input.GetKeyDown(KeyCode.S)){
speed++;
if (speed>maxSpeed)
speed=maxSpeed;
}else{
speed–; //decelerate speed maybe?
}

This allows acceleration over time I suppose.