2D Limit player speed

Hello I am working on a endless runner.I am using InvokeRepeating for adding speed to my player but I have problem with it.I want to limit my max player speed to 20f. How can I do this?

Hi bud.

If you are using rigidbody to move use:

Rigidbody2D = rb;
public float maxVelocity = 20f

void FixedUpdate()
{
        if(rb.velocity > maxVelocity)
        {
               rb.velocity = maxVelocity
        }
}

Hope that solves your problem.

If you are using any other way of moving, feel free to let me know. i’ll help you.

If the player is moving up the screen use:

maxVelocity  = 20f;
if (rb.velocity.magnitude > maxVelocity) {
    rb.velocity = Vector2.up * maxVelocity;
}

If they’re moving left to right use:

maxVelocity  = 20f;
if (rb.velocity.magnitude > maxVelocity) {
    rb.velocity = Vector2.right * maxVelocity;
}

To increase performance, you can replace the (rb.velocity.magnitude > maxVelocity) with (rb.velocity.sqrMagnitude > Mathf.Pow(maxVelocity, 2))

If this works please mark the question answered. If it doesn’t please ask any questions I’m happy to help :slight_smile:

Assuming you want limit the speed on the x axis

public float maxVelocity = 20f;

//put this inside your invoke repeating
    if(rb.velocity.x  > maxVelocity)
    {
        rb.velocity = new Vector2(maxVelocity, rb.velocity.y);
    }