- Home /
How to decelerate a 2D object?
I have a simple 2D object that I want to slowly decelerate before it stops. This is the script that is attached to the object (it's just the basic movement):
void Update () {
float horizontal = Input.GetAxis ("Horizontal");
float vertical = Input.GetAxis ("Vertical");
Vector3 move = new Vector3 (horizontal, vertical, 0.0f);
transform.position += move * speed * Time.deltaTime;
}
Comment
Answer by UnityCoach · Feb 20, 2017 at 10:03 AM
Hi,
you need to detect if your Vector3 is zero (if the player has released) the input and interpolate to zero then. Something like this :
private Vector2 _input;
private Vector3 _move;
void Update ()
{
_input = new Vector2 (Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"));
if (_input != Vector2.zero)
{
_move = (Vector3) _input;
}
else
{
_move = Vector3.Lerp (_move, Vector3.zero, decelerationSpeed * Time.deltaTime);
}
transform.Translate (_move * speed * Time.deltaTime);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612111419im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Uneven speed in 2d movement script 2 Answers
I need to change the animation when my speed increases in a 2D game 0 Answers
Stop Player movement when bool changes 2D 3 Answers
How to make an object move to another object's location in a 2d game? 2 Answers