how do you use rigidbody.SetVelocity without affecting jumping?

I’ve been trying to get my character movement script to work, and so far the movement on the x and z axis are fine, but they interfere with the jumping. I know why - “V” is constantly setting the y velocity to 0 then adding gravity, but i dont know how to fix it without changing the movement completely.

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

public class movement : MonoBehaviour
{
    public Rigidbody r;
    public float speed = 300f;
    public Vector3 V;
    public float jump = 320f;

    void FixedUpdate()
    {

        if (Input.GetKey("w"))
        {
            V.x += transform.forward.x * speed * Time.deltaTime;
            V.z += transform.forward.z * speed * Time.deltaTime;
        }
        else if (Input.GetKeyUp("w"))
        {
            V.x -= transform.forward.x * speed * Time.deltaTime;
            V.z -= transform.forward.z * speed * Time.deltaTime;
        }

        if (Input.GetKey("s"))
        {
            V.x -= transform.forward.x * speed * Time.deltaTime;
            V.z -= transform.forward.z * speed * Time.deltaTime;
        }
        else if (Input.GetKeyUp("s"))
        {
            V.x += transform.forward.x * speed * Time.deltaTime;
            V.z += transform.forward.x * speed * Time.deltaTime;
        }

        if (Input.GetKey("a"))
        {
            V.x -= transform.right.x * speed * Time.deltaTime;
            V.z -= transform.right.z * speed * Time.deltaTime;
        }
        else if (Input.GetKeyUp("a"))
        {
            V.x += transform.right.x * speed * Time.deltaTime;
            V.z += transform.right.z * speed * Time.deltaTime;
        }

        if (Input.GetKey("d"))
        {
            V.x += transform.right.x * speed * Time.deltaTime;
            V.z += transform.right.z * speed * Time.deltaTime;
        }
        else if (Input.GetKeyUp("d"))
        {
            V.x -= transform.right.x * speed * Time.deltaTime;
            V.z -= transform.right.z * speed * Time.deltaTime;
        }

        if (Input.GetKeyDown("space"))
        {
            r.AddForce(0, jump * Time.deltaTime, 0);
        }

        r.velocity = V + Physics.gravity;

        V = new Vector3(0, 0, 0);


    }
}

You could just set “V”'s y member to r.velocity.y after adding the jump force.

example code:

if( Input.GetKeyDown("Space") )
{
       r.AddForce( 0, jump * Time.deltaTime, 0 );
       V.y = r.velocity.y;     // here, just add that
}

That should do it.

I tried that before. The problem is that it is still affecting the Y velocity of the object. The only things i want to affect it are the jumping and gravity.
Also, I added collision detection and somehow it works fine now except that the camera glitches to the side sometimes.