I fly, why?,I fly why?

I fly up when i look and press a movement key. But i dont want to go up. I just want a normal walking script
Heres mine.
public class PlayerMove : MonoBehaviour
{
public float moveSpeed = 2.0f;
public Transform playerBody;
public Transform mainCamera;
public CharacterController controller;

    // Update is called once per frame
    void Update()
    {
        KeyboardMovement();
    }
    void KeyboardMovement()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 sidewaysPos = Camera.main.transform.right;
        Vector3 forwardPos = Camera.main.transform.forward;
        Vector3 move = sidewaysPos * x + forwardPos * z;
        transform.Translate(move * moveSpeed * Time.deltaTime);
    }
}

,I want a normal movement script. I’ve kinda made my own because the other ones wouldn’t work.
But whenever i look up iand press w (any movement key) I go in the air. I want to fix this but idk how.

Heres my code
public class PlayerMove : MonoBehaviour
{
public float moveSpeed = 2.0f;
public Transform playerBody;
public Transform mainCamera;
public CharacterController controller;

// Update is called once per frame
void Update()
{
    KeyboardMovement();
}
void KeyboardMovement()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 sidewaysPos = Camera.main.transform.right;
    Vector3 forwardPos = Camera.main.transform.forward;
    Vector3 move = sidewaysPos * x + forwardPos * z;
    transform.Translate(move * moveSpeed * Time.deltaTime);
}

}

You really don’t want to use transform.Translate. If you’re already using a character controller, use the Move() function on the controller.


You would have to get the correct directions when a key is pressed, however. Right now, you’re getting the camera’s forward direction, which is the look direction. So you’ll just move where you’re looking, no matter the axis. You only really want to do that for the y-axis. The x and z axis should be controlled using Input.GetAxis("Horizontal"); or something like that.


There are already some great example character controller movement scripts and tutorials on youtube, Unity Learn, the Docs, and elsewhere, so I would go check some of those out if you can’t understand what I wrote. @stowellgray

You are using the forward, left, and right direction of the camera, so if you point the camera up, then forwardPos in your script will be up and that is where you will move. Usually the way to do this is to have a player object that can only look left or right but not up or down. Then as a child of this you have the camera. Moving the camera left and right will turn the whole character left and right, but moving the camera up and down will only move the camera up and down. Then just use the trasform.right and transform.forward of your character and NOT your camera.