Trying to prevent 2d character from sliding after landing from a jump (2d platformer)

I am creating a 2d platformer. I allow the player to move the character forward when grounded or if it is going up (so when going down you cant move forward) using AddForce. My issue is that after landing the character keeps sliding forward (until the added forward force runs out due to drag). I want to prevent sliding so I added this code:

if(characterGrounded && horizontalMove==0){
characterRB.velocity = new Vector2(0f, 0f);
}

(Where horizontalMove is updated to be 1 if you press right key, -1 if you press left key, and 0 if you press neither.)
To prevent any grounded movement not resulting from key presses by player.

But for some reason the character keeps sliding.

Any ideas or suggestions on how to fix this code or prevent sliding? I tried adding force in the opposite direction but it is much more difficult to fine-tune

With floats you should never check for an equal value of 0, because the statement could never be true due to floating point precision. Either use Mathf.Approximately to compare floats or check if the value (in this case) is bigger than -0.1f and smaller than 0.1f.
Not saying this is the issue but it’s always good practice.
Also, you can shorten “new Vector2(0f, 0f)” to “Vector2.zero”.

Changed code to:

if(characterGrounded && (horizontalMove<0.1f && horizontalMove>-0.1f)) {
Debug.Log("Entered If");
characterRB.velocity = Vector2.zero;
}

And now it sometimes works. I want to completely remove sliding.

Note that I use 2 raycasts from the edges of the box collider around the player character sprite to check if the character is grounded. I use AddForce to jump and move forward when jumping. I use velocity to move when grounded.

1 Like