CAMERA - Ignoring Y?

I have a MouseLook type script for my camera, but I’m also trying to have my player move in the direction the camera is pointing while ignoring the Y axis. haha

I’m pretty novice to Unity and JavaScript and I’m sure it’s a pretty simple solution, but as of now I have the player moving in the direction of the camera. But as soon as I start moving backwards and looking down, my player starts moving up the Y axis.

I’ve looked through tutorials and can see the other scripts are setting it to 0. ( variable.y = 0; ) This doesn’t seem to work with my code. And where I’m new to Unity I’m not sure what the error I’m getting is telling me. :expressionless:

This is what I have so far:::

var speed = 10;
var cam = Camera.main.transform;
//cam.y = 0;                   <--- This and the one below it is what I've tried but I get an error.
//cam.Normalize()

if(canPlay)
	{
		Screen.lockCursor = true;
		Screen.showCursor = false;
		var moveForward = Input.GetAxis("Vertical") * speed;
		var moveSideways = Input.GetAxis("Horizontal") * speed;
		
		moveForward *= Time.deltaTime;
		moveSideways *= Time.deltaTime;
	
		transform.Translate(cam.forward*moveForward,Space.World);
		transform.Translate(cam.right*moveSideways,Space.World);
        }

Any help would be greatly appreciated! :slight_smile:

at least 2 ways to handle this:
Put your camera under another transform and to the movement and ‘body’ rotation on that transform and have up/down rotation on the camera ‘head’ .
or
flatten cam.forward by multiplying the Y element by 0 and normalizing. I think this is what you are trying to do above, but it should look more like this, as you want to create a custom vector for forward, not try to modify the camera’s forward (which is protected from modification)

var myforward = Camera.main.transform.forward;
myforward.y = 0;                 
myforward.Normalize();
transform.Translate(myforward*moveForward,Space.World);

and the same thing for your right vector.
Also, ther are a lot of posts like this in the forum. do a search for forward

Sweet. Thanks pakfront!

I did try looking for posts on this and didn’t find much. Maybe I was searching the wrong keywords. :stuck_out_tongue:

This is what I ended up with.

if(canPlay)
	{
		Screen.lockCursor = true;
		Screen.showCursor = false;
		var moveForward = Input.GetAxis("Vertical") * speed;
		var moveSideways = Input.GetAxis("Horizontal") * speed;
		
		var camForward = Camera.main.transform.TransformDirection(Vector3.forward);
		camForward.y = 0;
		camForward.Normalize();
		
		var camSideways = Camera.main.transform.TransformDirection(Vector3.right);
		camSideways.y = 0;
		camSideways.Normalize();
		
		moveForward *= Time.deltaTime;
		moveSideways *= Time.deltaTime;
		
		transform.Translate(camForward*moveForward,Space.World);
		transform.Translate(camSideways*moveSideways,Space.World);
	}