How to limit player speed?

Hi, I’m new to unity, and Now I’m making a simple 2D endless runner…I’m following the live training tutorial and I want the player’s speed to increase over time, so I Use ;

void FixedUpdate (){

		speed = 12 + (Time.time*0.05f);
		rigidbody2D.velocity = new Vector2 ((speed), rigidbody2D.velocity.y);
		isGrounded = Physics2D.OverlapCircle(GroundCheck.position, 1, groundlayers);
		isHit = Physics2D.OverlapCircle (HitCheck.position, 1, obslayers);

thing is, I want to do two things ;

  1. Limit the speed to 20, so It won’t go too fast. (anything more would cause the player to move faster than the spawner can spawn the platforms)
  2. Reset the speed when the player hits an obstacle, which is why there’s an isHit bool.

I’ve tried to use while loop, to no avail, I’m guessing it’s because of the speed function I made above…Thanks in advance

In order to limit your speed use the Mathf.Clamp function and in order to reset the current speed you need to set it to 0:

public class PlayerController : MonoBehaviour
    public float speed = 12;
    public float maximumSpeed = 20;
    public float minimumSpeed = 0;

    private float m_currentSpeed;

    private bool isGrounded;
    private bool isHit;
    // Use this for initialization
    void Start()


    void Update()
        m_currentSpeed = speed * Time.time;
        m_currentSpeed = Mathf.Clamp(speed, minimumSpeed, maximumSpeed);

        rigidbody2D.velocity = new Vector2((m_currentSpeed), rigidbody2D.velocity.y);
        isGrounded = Physics2D.OverlapCircle(GroundCheck.position, 1, groundlayers);
        isHit = Physics2D.OverlapCircle(HitCheck.position, 1, obslayers);
        if (isHit)
            m_currentSpeed = 0;


However if you do that the way you are doing it right now the current speed will stay 0 always when the circle collider overlaps a target and you won’t be able to move. But i suppose this is what you are trying to achieve. From here you should only allow only left and right movement i guess and it will be ok.