How To Stop Velocity?

Hi! So I just started using Unity and I’m still very new to it. So far I’ve just been learning various scripts for basic movement in 2D. And there’s one that I like because it doesn’t allow diagonal movement when pressing WASD, but I haven’t figured out how to make the velocity stop when the keys aren’t being pressed. The object just continuously moves. I imagine there’s a simple way to fix it, but I’ve been at it for over a day and I haven’t come up with anything. Thank you for any help!

(Also just ignore the two lines in //. That’s just another movement script I wanted to keep in there.)

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

public class Player : MonoBehaviour
{
    [SerializeField] private float speed;
    private Rigidbody2D body;
    
    
    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
        
    }

    private void Start()
    {
        

    }

    private void Update()
    {
        //body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
        //body.velocity = new Vector2(body.velocity.x, Input.GetAxis("Vertical") * speed);

        
        if(Input.GetKeyDown(KeyCode.A))
        {
            body.velocity = Vector2.left * speed;
        }
        
        if(Input.GetKeyDown(KeyCode.D))
        {
            body.velocity = Vector2.right * speed;
        }

        if(Input.GetKeyDown(KeyCode.W))
        {
            body.velocity = Vector2.up * speed;
        }

        if(Input.GetKeyDown(KeyCode.S))
        {
            body.velocity = Vector2.down * speed;
        }
        
    }

}

That’s because you’re declaring what velocity should be. So last thing you press is what it will stay as until something tells it to stop. Best way to handle these types of issues is to say:

private void Update()
     {
         body.velocity = Vector2.zero;

         if(Input.GetKey(KeyCode.A))
         {
             body.velocity = Vector2.left * speed;
         }
         
         if(Input.GetKey(KeyCode.D))
         {
             body.velocity = Vector2.right * speed;
         }
 
         if(Input.GetKey(KeyCode.W))
         {
             body.velocity = Vector2.up * speed;
         }
 
         if(Input.GetKey(KeyCode.S))
         {
             body.velocity = Vector2.down * speed;
         }
         
     }

This way the very first set is to make the velocity equal nothing, then the moment you press something, it will override that declaration of zero. And when you don’t press anything, or stop pressing, it will revert to zero. But always leave null standings before code to revert to. As if putting it at the bottom of your presses, the value will always be zero.

Also noticed you had GetKeyDown, I think you want GetKey