So, I’m working with the Unity 2D controllers (If I recall correctly it was the same way with 3D controllers as-well) that after you added force to the object, it gradually decreased based on “Friction” and “Gravity” or whatever factors that were implemented in the game at the time.
I’m working on a 2D game where the character needs to stop moving immediately once the button is released, at first I thought (Oh this should be simple, lets just set the velocity to Vector3.zero when the button is released) but this started a whole new problem, if the player hits the A key to go left, before releasing the D key that was taking him right, it creates a stutter.
I attempted doing the following
float direction = Input.GetAxis ("Horizontal");
// If the player is moving to the Right.
if (direction > 0)
{
rigidbody2D.velocity = new Vector2(1 * playerSpeed, rigidbody2D.velocity.y);
}
// If the player is moving to the Left.
else if(direction < 0)
{
rigidbody2D.velocity = new Vector2(-1 * playerSpeed, rigidbody2D.velocity.y);
}
else if(direction == 0)
{
rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
}
However, this does not stop it immediately, instead it waits about a second (roughly) before stopping.
Another thing that I tried is this
if(Input.GetKeyDown (KeyCode.D))
rigidbody2D.velocity = new Vector2(1 * playerSpeed, rigidbody2D.velocity.y);
if(Input.GetKeyDown (KeyCode.A))
rigidbody2D.velocity = new Vector2(-1 * playerSpeed, rigidbody2D.velocity.y);
if(!(Input.GetKey (KeyCode.A)) && !Input.GetKey(KeyCode.D))
rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
This works, however I don’t see how it would work with mobile.
It also glitches, if I hold down A, then D, then release D and hit A, it continues to go right