How to increase and decrease walking speed in Unity?

Viewed 30

I am creating a Jump 'n' Run game and I want my character to be able to increase its walking speed, just like in typical Mario games. I wanna do it by holding the right arrow and decrease it by holding the left arrow and the longer you hold it, the quicker/slower you get until you get to your max/minimum/default speed. However, I can't figure out how to do it.

This is the code of my current movement:

     void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal"); // left or right arrow

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }
}
private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

How can I achieve this?

0 Answers
Related