I don’t quite understand the reason Mathf.Sign() works. I tried the code with and without the Mathf.Sign(). Keeping it in the code makes my Player stop when I let go of the key. But when I remove Mathf.Sign from my code, my Player skids a bit and doesn’t stop automatically. Why does this happen?
As the Mathf.Sign() documentation says
Return value is 1 when f is positive or zero, -1 when f is negative.
Taking the Mathf.Sign() out of that code
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y);
makes it so you replace the velocity with a new vector2 that has the same value as before.
Having the Mathf.Sign there causes you to replace velocity with a vector that has an x-component of -1 or 1 depending on whether velocity.x was less than zero or greater.
If you are trying to limit x-velocity to maxSpeed
you should multiply that -1 or 1 with maxSpeed
rb2d.velocity = new Vector2(maxSpeed * Mathf.Sign(rb2d.velocity.x), rb2d.velocity.y);