Keeping camera-relative movement on the X and Z axes?

Evening, everyone.

I’m currently in the process of re-writing my movement code from scratch. It’s your typical camera-relative movement: W is always away from the camera, S is always towards, and A/D is to either side, as you’d expect.

The issue I’m running into is that, since the camera is freely controlled by the mouse, you’re able to move it above and below the character, and they’re still able to go towards and away from it. This is resulting in them either trying to run through the ground, slowing them down, or taking flight into the air.

Is there any way to prevent this, and make them only move on the XZ plane?

The code :

function Update () {
	controller = GetComponent(CharacterController);

	if (controller.isGrounded  canMove) {
		moveDirection = LevelProperties.mainCam.transform.TransformDirection
		(Vector3(Input.GetAxis("Horizontal"),0, Input.GetAxis("Vertical")));
		moveDirection = transform.TransformDirection(moveDirection);
		moveDirection *= moveSpeed;
        
	if (Input.GetButton ("Jump")) {
		moveDirection.y = jumpHeight;
        }
    }
    
	moveDirection.y -= gravity * Time.deltaTime;
    
	controller.Move(moveDirection * Time.deltaTime);
}

I recommend adjusting the hieght of the moveDirection variable to the current character height between lines 6 and 7.

Example: moveDirection.y = transform.position.y;

Hope this helps

That seems like it would work well, but I’ve got something figured out.

I’d never actually considered just revamping the way the movement works before, but I’ve found that I can use moveDirection to turn the player in conjunction with Quaternion.LookRotation, and then just use the moveSpeed with transform.Forward to make them go in the direction they’re turning in.

I seriously appreciate the help, regardless.