Can't properly set x velocity of an object

I’ve run into an issue where I can’t properly clamp the x velocity of the player, right now I’m trying to max out what the x variable of the player’s velocity can be to maxSpeed, but, unfortunately, I can’t use clampMagnitude because that clamps the y velocity as well, which means the player won’t be able to jump correctly anymore, right now the part of my script that handles x axis movement looks like this

if (Input.GetKey(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.A))
        {
            float xClamp = 0;

            xClamp = Mathf.Clamp(PlayerSpeed * Time.deltaTime, 0, maxSpeed);

            rb.AddForce(new Vector2(xClamp, 0));
        }

        if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.D))
        {
            float xClamp = 0;

            xClamp = Mathf.Clamp(PlayerSpeed * -1 * Time.deltaTime, maxSpeed * -1, 0);

            rb.AddForce(new Vector2(xClamp, 0));
        }

it’s currently in the update function, as you can see, even using Mathf.Clamp doesn’t work because the addforce just keeps adding onto the clamped variable since that’s how AddForce works, would anyone know how to clamp only the x velocity correctly? and can you clamp AddForce somehow? I already tried rb.velocity.set, and I couldn’t get that to work either.

A lot of problems with this code:

  • You’re doing AddForce in Update() which is a mistake. AddForce calls of this style should be done only in FixedUpdate to ensure consistent behavior of the game at different framerates.
  • You’re not clamping the velocity at all here, you’re instead clamping the force that you are applying to the object. This does nothing to limit the velocity itself as you are seeing.

You’re overthinking this:

Vector3 vel = rb.velocity;
vel.x = Mathf.Clamp(vel.x, -maxSpeed, maxSpeed);
rb.velocity = vel;

Thank you, that fixed it