Deceleration of an object.

Hi Unity users,

I’m trying to make an object decelerate when the player takes his finger off the button for accelerating. At the moment I’m using transform.Translate to move the object. I could simply add a force because I added a rigid body to my object. I tried a Yield WaitForSeconds then it would add drag to the object but that spawned all sorts of errors. Take a look at my code here.

``````var acceleration: float = 100;
var speed: float = 0.1;
var maxspeed: float = 200;
var boost: float = 0;
var reverse_speed: float = 0.1;

function Update () {

if(speed >= maxspeed){
speed=maxspeed;
}

transform.Translate(Vector3.forward * speed * Time.deltaTime);
if(Input.GetAxis("Vertical")){speed = speed + acceleration;}

if(Input.GetAxis("Brake")){speed = speed - reverse_speed;}

Debug.Log(speed);
}
``````

Thanks
-WarHawk.

With your current approach, it could simply be like “if vertical, + acceleration, else if brake, - reverse_speed, else - drag”.

If you’d want to deal with this by using physics forces and stuff, don’t use translate as well.

I’m using AddForce instead of transform now so I can properly add drag. Iv’e made an deceleration function that adds drag after a certain time that a button comes up. The only problem is that it doesn’t work when my button comes up.

can you put your new code using drag and forces? I’m using that in my games and it works correct

``````var acceleration: float = 100;
var speed: float = 0.1;
var maxspeed: float = 200;
var boost: float = 0;
var reverse_speed: float = 0.2;
var TimeVar: float = 1;
var deceleration: float = 0.2;

function Update () {

if(speed >= maxspeed){
speed=maxspeed;
}

if(Input.GetAxis("Vertical")){speed = speed + acceleration;}

if(Input.GetAxis("Brake")){speed = speed - reverse_speed;}

Debug.Log(speed);
}

function decelerate () {
if(Input.GetKeyUp("w")){
yield WaitForSeconds (TimeVar);
rigidbody.drag = 5;
}
}
``````

Basically just a simple function added but I can’t get it work.

Ok, but when do you use this function Decelerate?. I only see the function definition.

I think you have to use it at least one time in the Update.
Just try to put into the Update:

if(Input.GetKeyUp(“w”)){
//yield WaitForSeconds (TimeVar); I don’t know if a Yield is a good Idea in a Update, however.
rigidbody.drag = 5;
}

Putting it in the update brings up coroutine errors, it doesn’t like it at all. its to do with the yield WaitForTime.

You don’t want to yield your Update anyway. Call the decelerate function instead, which should do the yield and then adjust drag.

I’m not sure why you want to delay applying drag though. Drag is more of a constant factor, which becomes more pronounced the faster you go.

I’ve sort of fixed it now so it does decelerate and stop but now having the problem with reducing the speed as it stops.