Answers for "Add acceleration and deceleration for top down 2D movement."http://answers.unity.com/questions/1587925/add-acceleration-and-deceleration-for-top-down-2d.html
The latest answers for the question "Add acceleration and deceleration for top down 2D movement."Answer by Klarzahshttp://answers.unity.com/answers/1587992/view.html
Hi @RealmsDev , you can achieve this by faking a *very* basic acceleration. A (untested) code snippet for this would be:
float acceleration = 1;
float curHorizontalMovement = 0;
float curVerticalMovement = 0;
flaot MinMovement = 0.001f;
...
void FixedUpdate(){
if(horizontal != 0)
//accelerate in direction of keypress
curHorizontalMovement += acceleration * horizontal;
else
//we dont detect any keypress: "decay" the velocity by half
curHorizontalMovement /= 2;
//if we keep decaying, we will walk for a long time, but always slower. To combat this, we simply set a minimum threshold
if( curHorizontalMovement < MinMovement)
curHorizontalMovement = 0;
//similar for the vertical movement
...
body.velocity = new Vector2(curHorizontalMovement * moveSpeed, curVerticalMovement* moveSpeed);
}
This approach has multiple downsides:
- It doesn't feel natural: most acceleration isnt linear in the real world
- If you are walking at fullspeed in one direction and want to do a 180, you would need to decelerate and then accelerate in the opposite direction. This takes time
- Decaying the velocity by half if you dont have any input is unnatural as well
As a side node: you dont want to check for zero for a float with "= 0", as this is nearly never the case ([explanation][1]). Instead, set a threshold, under which you just assume it to be zero.
Hope this helps
[1]: https://stackoverflow.com/a/485741/10662062Tue, 08 Jan 2019 14:28:53 GMTKlarzahsAnswer by Ady_Mhttp://answers.unity.com/answers/1587984/view.html
Before you even think about moving an object, focus on just getting a float value to increase towards max while a key is pressed and drop to towards zero when the key is up.
This example also lets you go under 0, in case you need that.
To test it, place the script on an empty object and use the controls **A (negative)** and **D (positive)**, and **Shift** to reach the destination value **twice as fast.**
Max in this case is always -1 or 1. You can easily multiply this by any number as needed (for example, multiply it by maxSpeed then translate the object).
public float value;
public float timeFromZeroToMax = 2; // How long it takes to reach max
private void Update ()
{
float moveTowards = 0;
float changeRatePerSecond = 1 / timeFromZeroToMax * Time.deltaTime;
if (Input.GetKey (KeyCode.A))
{
moveTowards = -1.0f;
}
else
if (Input.GetKey (KeyCode.D))
{
moveTowards = 1.0f;
}
if (Input.GetKey (KeyCode.LeftShift))
{
// Reach destination value twice as fast
// when Shift is held down
changeRatePerSecond *= 2;
}
value = Mathf.MoveTowards (value, moveTowards, changeRatePerSecond);
}Tue, 08 Jan 2019 14:15:50 GMTAdy_M