# How do I get a value to increment smoothly?

How do I get a variable that’s set to a value to increment smoothly (or smoothly ease/ fade) to a target value?
Such as speeding or slowing a plane during flight.
Here’s my code below:

``````#pragma strict

var speed : int;
var maxSpeed : int = 100;
var minSpeed : int = 0;
var startSpeed : int = 50;
var camera : GameObject;
var zoomCamera : GameObject;
var enemyKillRatio : int = 0;
var health : int = 100;
var reset : boolean = false;

function Update () {

//start speed
speed = startSpeed;

//constant forward
transform.Translate(0, 0, speed * -1 * Time.deltaTime); //speed set at 50 here.

//movments; speedup
if (Input.GetKey("c")) {
//smoothly incrimint speed up by 1.
speed = ++ speed;//needs incrment speed.

transform.Translate(0, 0, speed * -1 * Time.deltaTime);
}
//movements; slowdown
if (Input.GetKey("v")) {
//smoothly deincrament speed by 1.
speed = -- speed;//need increment speed.

transform.Translate(0, 0, speed * Time.deltaTime);
}

//limit speed
if(speed >= maxSpeed){
speed = maxSpeed;
}
if(speed >= minSpeed){
speed = minSpeed;
}

}
``````

How do I get my movement speed up and movement slow down to smoothly ease to a max or a minimum value?
The output of the code so far allows the player fly forward. When c key is pushed, the player goes faster (until maxSpeed = 100). When v key is pushed the player stops instantly (when minSpeed = 0).

Maybe you can try to use Mathf.Lerp to smooth out?

Something like this: (untested)

``````speed = Mathf.Lerp (speed, minSpeed, smoothTime);
``````

when you press the C key. And then this to smooth to max speed:

``````speed = Mathf.Lerp (speed, maxSpeed, smoothTime);
``````

var lastInc = 0.0;
var toInc = 0;
while(Input.GetKeyDown(KeyCode.C))
{
if(( Time.time > lastInc + 0.05))
{
toInc++;
lastInc = Time.time;
}
}

Set it up to wait .05 seconds in between incrementation.