- Home /
Im using add force to make a 'ship' go forward, if i release the key is there any way to slow it gradually?
I've got some simple code moving a 'ship' around a screen. It uses AddForce() to go forward and AddTorque() to go left and right. It's all working, however if i release my forward key, the ship immediatly stops, is there any way to gradually decrease it's force or detect if i've released the key and slowly drop the force??
This is in javascrpit just incase you didn't know.
var moveUp : KeyCode;
var turnRight : KeyCode;
var turnLeft : KeyCode;
var speed : int = 1;
function Update () {
if (Input.GetKey(moveUp)) {
rigidbody2D.AddForce(transform.up * speed);
Debug.Log("MoveUp");
}
else {
rigidbody2D.velocity.x = 0;
rigidbody2D.velocity.y = 0;
}
if (Input.GetKey(turnRight)) {
rigidbody2D.AddTorque(-1.2f);
}
if (Input.GetKey(turnLeft)) {
rigidbody2D.AddTorque(1.2f);
}
}
My Code
Answer by robertbu · Mar 18, 2014 at 07:24 PM
Take out lines 15 - 19. Then select the object this script is attached to in the Inspector, and adjust upward the 'Drag' variable in the Rigidbody component. You may also have to increase the value of 'speed' in the script above. Note that 'speed' should be a float (not an int) and it doesn't represent the speed of your object but rather the amount of force to apply. Also your code above should be in FixedUpdate() not Update().
You could instead of the above, replace these two lines:
rigidbody2D.velocity.x = 0;
rigidbody2D.velocity.y = 0;
With:
rigidbody2D.velocity = rigidbody2D.velocity * 0.95;
The '0.95' will need to be adjust for how quickly you want to slow down.