- Home /
Lock translation on the Y-axis
Hi guys! Right now I'm making my camera script, and I have encountered a problem. I'm using this script right now to move the camera:
if (Input.GetKey (KeyCode.W)) {
Target.transform.Translate(Vector3.forward * MovementSpeed);
}
And it works fine. The only problem is that because the camera is tilted, it goes a bit down when I move the camera. How do I lock the translation on the Y axis so if the camera is tilted it's still only moving on the z-axis on y = 10.
I hope this wasn't to lousy written... Thanks,
Niklas
Answer by robertbu · Nov 25, 2013 at 07:14 PM
if (Input.GetKey (KeyCode.W)) {
var v3 = Target.transform.forward;
v3.y = 0.0;
Target.transform.Translate(v3 * MovementSpeed * Time.deltaTime, Space.World);
}
If this code is executed in Update(), then you should introduce 'Time.deltaTime' to keep your code consistent across different frame rates. MovementSpeed will then need to increase and represents units per second.
Just to clearify for the poor people who will find this answer from Google, he forgot an "f" after 0.0 :) Not a biggie, just to clearify.
The 'f' is only necessary for C#. I cound not tell from from the original question C# or Javascript so wrote the answer for Javascript. If it was C#, I would have do this as well (though not strictly necessary):
Vector3 v3 = Target.transform.forward;
Yeah, just realised that :P Well, it was a good answer anyways. Thanks!
Answer by PhilRousse · Nov 25, 2013 at 07:12 PM
The hackish way would be to do this:
if (Input.GetKey (KeyCode.W)) {
Target.transform.Translate(Vector3.forward * MovementSpeed);
Target.transform.position = (Target.transform.position.y, 10, Target.transform.position.z
}
But I'm sure their a better way by modifying the forward vector. Like this
Vector3 movingVector = Vector3.forward;
movingVector.y = 0;
That code is untested.
Answer by diegzumillo · Nov 25, 2013 at 07:17 PM
Easiest way to do that is to define a new variable like Vector3( Vector3.forward.x, 0, Vector3.forward.z);
That, however, will have limited uses, as you may want it to move in y occasionally. A little more context would help me help you better :P for example, is this for a 3rd person camera?
Your answer
Follow this Question
Related Questions
Lock the screen 1 Answer
Lock cursor everywhere not center,how? 1 Answer
Quaternion LookRotation/Slerp Axis Lock 3 Answers
Help with clearing bugs in this C# script 1 Answer
Modifying the pause menu to have screen.lockcursor on at start 1 Answer