Happy New Year.
I have an issue that I can’t find a suitable solution for online. I want to be able to look at an object and be able to use the mouse to move forward and back, and to also pan the camera around the object. My code has worked fine up until I added the ability to pitch the camera up and down. Now, if the camera pitches up or down, and THEN I move forward, the camera moves towards or away from the object. The effect I want is to move the camera forward (world coords) while still pitched up or down. I do not want the camera to move towards the terrain or into the sky.
I understand that this is an issue with local vs world coords. If I change “Space.Self” to “Space.World” I get my desired effect (pitching up and down works in that the camera’s altitude does not change), but obviously the camera does not move forward in the direction I want.
if (depthTranslation.isActivated())
{
float translateZ = Input.GetAxis(mouseVerticalAxisName) * depthTranslation.sensitivity;
transform.Translate(0, 0, translateZ, Space.Self);
}
I tried various iterations of “camera.TransformDirection” in an attempt to convert the camera’s z direction from local to world coords, and then translate the camera in world coords, but that did not pan out.
I’m hoping that this is something relatively simple I’m just not seeing!
Thanks for looking.
Kelly
So you want what is forward projected only on the xz plane… ignoring any rotation up or down (around the x axis, looking up and down the y axis).
Take the camera forward, transform it to world coordinates, remove the y component (set it to 0), normalize the vector, translate in the direction.
var forw = transform.forward;
//get forward in world coords
forw = transform.InverseTransformDirection(forw);
//remove the y component (up down rotation)
forw.y = 0;
forw.Normalize();
//now append to global position, because forw is a unit vector, multiplying by translateZ makes the vector length = to translateZ
transform.position += forw * translateZ;
…I’m sitting here just about ready to hide in the corner because of embarrassment! I actually tried something similar, but set the x and y to zero and only used the z… no wonder the results were messed up!
I’ll give this a try and report back later. Thanks for the help!
Kelly
Many thanks!
Modified working code:
if (depthTranslation.isActivated())
{
float translateZ = Input.GetAxis(mouseVerticalAxisName) * depthTranslation.sensitivity;
cameraMovForward = camera.TransformDirection(Vector3.forward);
transform.Translate((cameraMovForward.x * translateZ), 0, (cameraMovForward.z * translateZ), Space.World);
}
Or forget the vector math nonsense and make your camera GameObject the child of another GameObject then use the parent’s transform to move and the child’s transform to pitch. 
1 Like