transform.forward giving unwanted movement

Hi all,

I’m working on a Virtual Reality project with the oculus where the player should simply move through the environment and can look around and interact with some objects.

How this, the movement in this case, will work is that the player will press a button (for now that’s “W”) and then move in the direction the player is looking.
I got that to work, sort of, with the following code (note: that I as well partially found on the internet):

	public float moveSpeed = 2f;

	void Update () {
		if (Input.GetKey (KeyCode.W))
			transform.position += Camera.main.transform.forward * Time.deltaTime * moveSpeed;

Problem with this code is that the player can move into the air or through the ground as the .forward, z axis, rotates with the direction the camera is facing. How can I only use the Y axis rotation of the camera so that the transform .forward will never point towards the ground or into the air?

Or are there other, more efficient, ways that I should know of? I tried looking it up, but didn’t find any solutions that worked for me so far.

Any advice would be highly appreciated.

You can just zero out the forward vector component that you want to ignore. If you’re moving on the x/z plane then you can zero out y, so the movement can’t happen in the y direction at all…

Vector3 forward = Camera.main.transform.forward;
forward.y = 0;  // zero out y, leaving only x & z
transform.position += forward * Time.deltaTime * moveSpeed;