(C#) how do i make a first-person controller script that just moves me on the X & Y axis?

hi! i am a complete novice when it comes to coding and only know the absolute basics. please bear this in mind while trying to help my clueless bum.

i’ve been trying to figure out how to get a first person controller working for a little physics game to learn things with, and while this script i’ve whipped up works fairly well, it has a problem. i’m trying to make a simple controller to move the character on the X and Z axis’ while also having full camera control, like any normal FPS.

my current setup’s camera controls work properly, and aside from that it adds force in the direction the camera is facing, but this leads to my character flying off into space if i look up or down. how do i go about clamping the movement range on this script so it strictly moves on the X and Y axis’? i feel like there’s a quick and effective way to do it, but with my limited knowledge of the C# language i am unsure of how to find it. surely there’s just a way to move horizontally?

my code:

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

public class camerafollowscript : MonoBehaviour {

    public Camera pubcam;

    public Rigidbody playerblock;

    public Vector3 offset;

    public float fwdForce = 5f;
    public float horiForce = 25f;
    public float revForce = 10f;

    Vector2 rotation = new Vector2(0, 0);
    public float speed = 3;

    // Use this for initialization
    void Start () {

	}
	
	// Update is called once per frame
	void Update () {

        rotation.y += Input.GetAxis ("Mouse X");
		rotation.x += -Input.GetAxis ("Mouse Y");
		transform.eulerAngles = (Vector2)rotation * speed;
        
        if (Input.GetKey(KeyCode.W))
        {
            playerblock.AddForce(pubcam.transform.forward * fwdForce);
        }

        if (Input.GetKey(KeyCode.S))
        {
            playerblock.AddForce(pubcam.transform.forward * -revForce);
        }

        if (Input.GetKey(KeyCode.A))
        {
            playerblock.AddForce(pubcam.transform.right * -horiForce);
        }

        if (Input.GetKey(KeyCode.D))
        {
            playerblock.AddForce(pubcam.transform.right * horiForce);
        }
        
    }
    
    private void LateUpdate()
    {
        pubcam.transform.position = playerblock.transform.position + offset;
    }
    
}

A quick fix is to go to your player’s rigidbody component, and under constraints tick the box for the Y axis under “freeze position”. Of course, if there are slopes in your game you’ll have to find a work around. You could watch this tutorial as it covers movement: Creating a first person shooter in Unity [RNDBITS-019] - YouTube I hope this helps!