This code is attached to a camera:
transform.position += Input.GetAxis("Vertical") * transform.forward * mod;
transform.position += Input.GetAxis("Horizontal") * transform.right * mod;
I've used .forward and .right because the player is able to rotate the camera on the Y axiz, thus no matter which way the camera is facing the forward key will always move the camera relatively forward, the left key will move it relatively left and so on. Just to clarify - I want it to move in local space, not world space so forward is the direction it's facing, not necessarily Vector3(0,0,1).
The camera is free roaming and has no parent or target to follow.
The problem is the camera has an X rotation of 45 to look down. Using transform.forward will thus modify it's height. There is also some scroll code to change the cameras height so I don't want to set the hight to a fixed value. How can I limit the movement to X and Z only, preferably without parenting it it an empty?
Update: this code works but it's not pretty, I'm sure there is a more elegant solution using Vector3.Project, as xyLe_ is suggesting. If I figure it out I'll add to his answer.
mod = Time.deltaTime * 30;
float yPos = transform.position.y;
pos = transform.position;
pos += Input.GetAxis("Vertical") * transform.forward * mod;
pos.y = yPos;
pos += Input.GetAxis("Horizontal") * transform.right * mod;
pos += Input.GetAxis("Mouse ScrollWheel") * transform.up * mod * -30;
I might talk nonsense right now, but it seems pretty simple to me:
Vector3 desiredDirection = Vector3.Normalize(new Vector3(transform.forward.x, transform.position.y, transform.forward.z))
Just project transform.forward
onto the x-z plane that is settled at the height of transform.position.y
. Doing this (usually) results in a slightly shorter vector, so you have to renormalize it.
To visualize:
If I understand you correctly, transform.forward
corresponds to the black vector and you want to have the green vector. By setting the y component of the black vector to the y component of the red dots positions y component, you get the purple vector, which has to be renormalized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With