- Home /
How to make an object slowly decelerate?
Im very new to coding so bear with me, im making a car game, with the car being a single block, so no fancy wheels or anything. I have the movement code down, now i need to somehow make it so when i press space bar, the 'car' slowly decelerates to a complete stop. Can someone help?
Heres the code:
public class scr : MonoBehaviour
{
public float thrust = 1.0f;
public Rigidbody rb;
public GameObject move;
public Vector3 offset;
public float angleBetween = 0.0f;
public Transform target;
void Start()
{
rb = GetComponent<Rigidbody>();
offset = transform.position - move.transform.position;
}
//movementcode
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
rb.AddForce(transform.forward * thrust);
if (Input.GetKey(KeyCode.S))
rb.AddForce(-transform.forward * thrust);
if (Input.GetKey(KeyCode.A))
transform.Rotate(0, -1, 0 * thrust);
if (Input.GetKey(KeyCode.D))
transform.Rotate(0, 1, 0 * thrust);
if (Input.GetKey(KeyCode.LeftShift))
rb.AddForce(transform.forward * thrust * 2, ForceMode.Acceleration);
}
void LateUpdate()
{
transform.position = move.transform.position + offset;
}
}
Thank you!
Answer by Anis1808 · Dec 07, 2019 at 11:44 PM
You could try to add a ForceMode.Impulse when you add the force rb.AddForce(/*force*/, ForceMode.Impulse);
Or you could simply add a deceleration that you control fully:
if (Input.GetKey(KeyCode.W)){
rb.AddForce(transform.forward * thrust);
}else if (Input.GetKey(KeyCode.S)){
rb.AddForce(-transform.forward * thrust);
}else{ //If no Input
rb.velocity = rb.velocity * 0.95f * Time.deltaTime; //Edit 0.95 with the value you want as long as it is smaller than 1 and bigger than 0
}
Answer by RadonRaph · Dec 08, 2019 at 10:12 AM
Hello @champion342,
If you use rigidbody simply increase the drag property and angular drag, you could also edit the physic material.
What you want is friction, to add friction simply substract a percent of the velocity each frame (like in late update) like this:
rb.velocity -= 0.1f*rb.velocity;
Hope that help,
Raph
Your answer
![](https://koobas.hobune.stream/wayback/20220612215844im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
vehicle not accelerating after braking 2 Answers
How to play sound when object stops moving? 1 Answer
vehicle moveing on the terrain 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
YES/NO Can I implement a bouncing effect on my vehicle using physics joints 0 Answers