Player keeps going when i release key

So, i have my player script but there’s just one problem now.
My character keeps going when i release key. Any fixes for this?
Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float moveSpeed;
    public float jumpHeight;

    Rigidbody2D myRigidbody2D;

    private bool isGrounded;
    public LayerMask groundLayers;

    void Start()
    {
        myRigidbody2D = GetComponent<Rigidbody2D>();

    }

    // Update is called once per frame
    void Update()
    {
        isGrounded = Physics2D.OverlapArea(new Vector2(transform.position.x - 0.5f, transform.position.y - 0.5f),
            new Vector2(transform.position.x + 0.5f, transform.position.y - 0.51f), groundLayers);

        //movement
        if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
        {
            Jump();
        }


        if (Input.GetKeyDown(KeyCode.UpArrow) && !isGrounded)
        {
            Jump();
        }


        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            myRigidbody2D.velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
        }


        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            myRigidbody2D.velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
           
        }
    }

    void Jump()
    {
        myRigidbody2D.velocity = new Vector2(0, jumpHeight);
    }
}

you can stop the moving if the buttons was released (Input.GetKeyUp)

if (Input.GetKeyUp (KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
        {
            myRigidbody2D.velocity = new Vector2 (0, myRigidbody2D.velocity.y);
        }

maybe is it better to use input.getaxis ?

float move = Input.GetAxis("Horizontal");
myRigidbody2D.velocity = new Vector2(moveSpeed * move, myRigidbody2D.velocity.y);
1 Like

That’s because you’re setting its velocity which is constant motion. In order to stop, do this:

Nevermind, @vakabaka beat me to it lol

Edit:

I would say that I have learned that shooting projectiles is nice with adjusting velocity, but it isn’t that great for movement. I actually made a video that provides source code that perhaps you’d be interested in adapting to your style.

1 Like