Why does my player randomly stop?

So, I’m making a 2D sidescroller game, and for some reason, my player character randomly stops abruptly, whether or not a movement key is being pressed. My code is:

using UnityEngine;

public class PlayerMovement : MonoBehaviour {
    public Rigidbody2D rb;
    public SpriteRenderer sr;
    private float t = 0.0f;
    private bool grounded = true;
    private int canJump = 0;
    public float X = 0.0f;
    public float Y = 0.0f;
    private void Start()
    {
        rb = GetComponent<Rigidbody2D> ();
        sr = GetComponent<SpriteRenderer> ();
    }
    // Update is called once per frame

    void Update () {
        if (X < 0.0f)
        {
            sr.flipX = false;
        }
        else if (X > 0.0f)
        {
            sr.flipX = true;
        }
        if (X > 0.0f)
        {
            X -= 0.5f;
        }
        if (X < 0.0f)
        {
            X += 0.5f;

        }
        if (Y > -7.0f)
        {
            Y -= 0.7f;
        }
        if (Input.GetKey("a"))
        {
            X = -7.0f;
        }
        if (Input.GetKey("d"))
        {
            X = 7.0f;
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if(grounded == true)
            {
                Y = 11.0f;
                grounded = false;
            }
        }
        
        rb.velocity = new Vector2(x: X, y: Y);
    }
    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.collider.tag == "ground")
        {
            grounded = true;
        }
    }
}

Note that I checked the colliders on both the ground and player and they do not seem to intersect when this happens.

Edit: Fixed horrendous formatting.

might you want to use void Update instead of fixedupdate.
aswell you could change on collisionenter2d to collisionstay2d so your character will be ground if collision is happening…


and just for readable reason format your code in your question.